Web Apiコントローラインタフェース操作戻りタイプ


操作復帰タイプ(ASP.NET Core Web APIにおけるコントローラ操作の復帰タイプ)応答データフォーマット(ASP.NET Core Web APIにおける応答データのフォーマット)Web API 2の操作結果は、データ転送対象(DTO)asyncおよびASPを作成する.NET MVC     * * 1、IHttpActionResult => json() Json(T content) Ok() Ok(T content) NotFound() Content(HttpStatusCode statusCode, T value) BadRequest() Redirect(string location)
[HttpGet]
public IHttpActionResult GetAllGrade()
{
    var result = Mapper.Map>(_gradeRepo.GetList(x => x.Status != "D"));
    return Json(result);
}

2、HttpResponseMessageを直接HTTP応答メッセージに変換する
public HttpResponseMessage Get()
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode .OK, "hello");
    response.Content = new StringContent ( "hello wep api", Encoding .Unicode);
    response.Headers.CacheControl = new CacheControlHeaderValue
    {
        MaxAge = TimeSpan .FromSeconds(600)
        };
    return response;
}

public Task ExecuteAsync(CancellationToken cancellationToken)
{
    var response = new HttpResponseMessage()
    {
        Content = new StringContent(_value),
        RequestMessage = _request
    };
    return Task.FromResult(response);
}

*3.その他のタイプは、シーケンス化された戻り値を応答の本文(Response Body)に書き込み、HTTPステータスコード200(OK)を返す*4、async Task
// GET api/Books/5
[ResponseType(typeof(BookDetailDTO))]
public async Task GetBook(int id)
{
    var book = await db.Books.Include(b => b.Author).Select(b =>
        new BookDetailDTO()
        {
            Id = b.Id,
            Title = b.Title,
            Year = b.Year,
            Price = b.Price,
            AuthorName = b.Author.Name,
            Genre = b.Genre
        }).SingleOrDefaultAsync(b => b.Id == id);
    if (book == null)
    {
        return NotFound();
    }

    return Ok(book);
}

public Task ExecuteAsync(CancellationToken cancellationToken)
{
    var response = new HttpResponseMessage()
    {
        Content = new StringContent(_value),
        RequestMessage = _request
    };
    return Task.FromResult(response);
}

* asp.net mvc
public async Task Index()
{
    var departments = db.Departments.Include(d => d.Administrator);
    return View(await departments.ToListAsync());
}

public async Task Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Department department = await db.Departments.FindAsync(id);
    if (department == null)
    {
        return HttpNotFound();
    }
    return View(department);
}

* * * 5、ASP.NET Coreでは、string、カスタムオブジェクトタイプ、IEnumerable、IAsyncEnumerable●IActionResultなどのWeb APIコントローラの操作戻りタイプオプションを提供します.操作中に複数のActionResult戻りタイプがある場合、IActionResult戻りクラスタイプを使用するのに適しています.●ActionResult**6、**7、*0、