ASP.NET WebAPI的返回

目录

1、WebAPI中方法的返回

webapi的方法可以返回的类型有:voidhttpresponsemessageIHttpActionResult自定义

1.1、Void

public class ValuesController : ApiController
{
    public void Post()
    {
    }
}

HTTP响应

HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 02:13:26 GMT

1.2、HttpResponseMessage

可直接创建返回的HttpResponseMessage,包括exception。

public class ValuesController : ApiController
{
    public HttpResponseMessage Get()
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("hello", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    } 
}

响应

HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT

hello

也可以直接在HttpResponseMessage包含域模型的数据

public HttpResponseMessage Get()
{
    // 生成自定义数据
    IEnumerable<Product> products = GetProductsFromDB();

    // 将数据直接赋值给HttpResponseMessage 
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
    return response;
}

1.3、IHttpActionResult接口

这个是异步执行操作。IHttpActionResult接口的定义

public interface IHttpActionResult
{
    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}

实现接口的类

public class TextResult : IHttpActionResult
{
    string _value;
    HttpRequestMessage _request;

    public TextResult(string value, HttpRequestMessage request)
    {
        _value = value;
        _request = request;
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage()
        {
            Content = new StringContent(_value),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

控制器

public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        return new TextResult("hello", Request);
    }
}

响应

HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT

hello

另外,系统会有一些内置的IHttpActionResult 实现类,包括:NotFound、Ok等。具体可参考MSDN:内置实现

public IHttpActionResult Get (int id)
{
    Product product = _repository.Get (id);
    if (product == null)
    {
        return NotFound(); // Returns a NotFoundResult
    }
    return Ok(product);  // Returns an OkNegotiatedContentResult
}

1.4、自定义

这个就是自定义的类型。
这里面就包含了:1、内容协商;2、异常处理(HttpResponseException )。异常处理可参见MSDN中的资料。异常处理资料

上一篇:ASP.NET Core WebApi基于JWT实现接口授权验证


下一篇:ASP.NET Core WebApi基于JWT实现接口授权验证