在WebAPI中HttResponseMessage作为消息返回,而在ApiController中我们经常讲四类数据作为返回值,void,object(可序列化),IHttpActionResult,HttpResponseMessage,
Void与object
Void:返回状态码200,无数据
Object: 返回状态码200,数据
IHttpActionResult
public interface IHttpActionResult
{
Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
}
WebAPI为我们定义了一IHttpActionResult接口,从命名我们就可以来它是作为Action执行的返回结果。
在WebAPI总已经定义了很多实现了IHttpActionResult的类:
这些类大致可以分为:只有状态码,重定向,实体序列化,错误信息,201Created等几类。
状态码
CodeStatusResult:指定状态码
BadRequestResult:400
OkResult:200
NotFoundResult:404
UnAuthorizedResult:401
ConflictResult:409
InternalServerErrorResult:500
重定向
状态码302,并返回重定向url
RedirectResult:按绝对路径
RedirectToRouteResult:按路由
WebApi为我们提供了一个UrlHelp类,可实现路由向绝对路径的转换
IDictionary<string, object> route = new Dictionary<string, object>();
UrlHelper helper = new UrlHelper(Request);
route["controller"] = "Figure";
route["action"] = "GetAll";
string AbsoluteUrl = helper.Link("DefaultApi", route);
实体序列化
FormattedContentResult<T>:自定义序列化方式与状态码
NegotiatedContentResult<T>:自定义状态码,根据请求头信息匹配序列化类型
OkNegotiatedContentResult<T>:状态码200,根据请求头信息匹配序列化类型
JsonResult<T>:状态码200,Json序列化
错误信息
ExceptionResult:500, eg: {"Message":"出现错误。","ExceptionMessage":"未实现该方法或操作。","ExceptionType":"System.NotImplementedException","StackTrace":null}
BadRequestErrorMessageResult:400,eg: {"Message":"Error"}
InvalidModelStateResult:400,Model绑定错误,eg: {"Message":"请求无效。","ModelState":{"argument":["值不在预期的范围内。"],"implemented":["未实现该方法或操作。"]}}
这三种类型最终都是装换成HttpError
201 Created
CreatedNegotiatedContentResult<T>与CreatedAtRouteNegotiatedContentResult<T>
返回"201 Created"的状态。
同时ApiController也为我们定义许多返回IHttpActionResult的方法
public abstract class ApiController
{
protected internal virtual InvalidModelStateResult BadRequest(ModelStateDictionary modelState);
protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);
protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value, MediaTypeFormatter formatter);
protected internal virtual FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType);
protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value, MediaTypeFormatter formatter, string mediaType);
protected internal CreatedNegotiatedContentResult<T> Created<T>(string location, T content);
protected internal virtual CreatedNegotiatedContentResult<T> Created<T>(Uri location, T content);
protected internal virtual CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName, IDictionary<string, object> routeValues, T content);
protected internal CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName, object routeValues, T content);
protected internal virtual InternalServerErrorResult InternalServerError();
protected internal virtual ExceptionResult InternalServerError(Exception exception);
protected internal JsonResult<T> Json<T>(T content);
protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings);
protected internal virtual JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings, Encoding encoding);
protected internal virtual NotFoundResult NotFound();
protected internal virtual OkResult Ok();
protected internal virtual OkNegotiatedContentResult<T> Ok<T>(T content);
protected internal virtual RedirectResult Redirect(string location);
protected internal virtual RedirectResult Redirect(Uri location);
protected internal virtual RedirectToRouteResult RedirectToRoute(string routeName, IDictionary<string, object> routeValues);
protected internal RedirectToRouteResult RedirectToRoute(string routeName, object routeValues);
protected internal virtual ResponseMessageResult ResponseMessage(HttpResponseMessage response);
protected internal virtual StatusCodeResult StatusCode(HttpStatusCode status);
protected internal virtual UnauthorizedResult Unauthorized(IEnumerable<AuthenticationHeaderValue> challenges);
protected internal UnauthorizedResult Unauthorized(params AuthenticationHeaderValue[] challenges);
}
HttpResponseMessage
HttpResponseMessage表示包括状态代码和数HTTP 响应消息。在整个WebAPI中HttpResponseMessage是作为最终的请求结果,自然HttpResponseMessag可以作为Action的返回结果。如果单从返回数据上看我们可以只关心状态码(StatusCode),内容(Content),头信息(Headers)。
public class HttpResponseMessage : IDisposable
{
public HttpResponseMessage();
public HttpResponseMessage(HttpStatusCode statusCode);
public HttpContent Content { get; set; }
public HttpResponseHeaders Headers { get; }
public HttpStatusCode StatusCode { get; set; }
}
其实WebAPI定义了一个ResponseMessageResult,这个类实现了IHttpActionResult接口,这个类只重载了一个构造函数,定义了一个HttpResponseResult的属性
public class ResponseMessageResult : IHttpActionResult
{
public ResponseMessageResult(HttpResponseMessage response);
public HttpResponseMessage Response { get; }
public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
其中WebAPI为我们定义很多HttpContent的派生类。
ByteArrayContent
FormUrlEncodedContent
MultipartContent
MultipartFormDataContent
StreamContent
StringContent
不管是Void,object,IHttpActionResult都将生成HttpResponseMessage。
IhttpActionResult接口中只定义了一个ExecuteAsync方法
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
所以IHttpActionResult可以很容易得到HttpResponseMessage
源码
Github: https://github.com/BarlowDu/WebAPI (API_3)