void | 返回204状态码 |
HttpResponseMessage | Convert directly to an HTTP response message. |
IHttpActionResult | Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. |
Other type | Write the serialized return value into the response body; return 200 (OK). |
1. void 返回204状态码
public void Get() { }
2.直接转化成http响应消息
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) };
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new { a=1,b=2});
//return response; return response;
3.IHttpActionResult 调用 ExecuteAsync 创建HttpResponseMessage,最后实现 public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)方法
常用类https://msdn.microsoft.com/en-us/library/system.web.http.results(v=vs.118).aspx,也可以自定义实现IHttpActionResult接口。
public IHttpActionResult Get() { return NotFound();//Ok() //return new TextResult("hello", Request); } } 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); } }
4.使用其他类型
public Product Get() { return new Product { Id = 1, Name = "我的商品" }; } } public class Product { public int Id { get; set; } public string Name { get; set; } }
如果上述出现异常,无法返回404错误码,可以使用过滤器标签处理。
本文参考:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results