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 提供以下 Web API 控制器操作返回类型选项
● 特定类型:如 string,自定义对象类型, IEnumerable,IAsyncEnumerable
● IActionResult:当操作中可能有多个 ActionResult 返回类型时,适合使用 IActionResult 返回类型
● ActionResult
*
*
6、
*
*
*
*
7、
*
0、

你可能感兴趣的:(.Net技术)