VAA*_*AAA 29 c# asp.net-mvc json httpresponse asp.net-web-api
我有一个Web API项目,我的方法总是返回HttpResponseMessage.
所以,如果它工作或失败我返回:
没有错误:
return Request.CreateResponse(HttpStatusCode.OK,"File was processed.");
Run Code Online (Sandbox Code Playgroud)
任何错误或失败
return Request.CreateResponse(HttpStatusCode.NoContent, "The file has no content or rows to process.");
Run Code Online (Sandbox Code Playgroud)
当我返回一个对象然后我使用:
return Request.CreateResponse(HttpStatusCode.OK, user);
Run Code Online (Sandbox Code Playgroud)
我想知道如何向HTML5客户端返回更好的封装respose,以便我可以返回有关事务的更多信息等.
我正在考虑创建一个可以封装HttpResponseMessage但也有更多数据的自定义类.
有没有人实现类似的东西?
Kal*_*ade 36
虽然这不是直接回答这个问题,但我想提供一些我认为有用的信息. http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx
HttpResponseMessage或多或少被IHttpActionResult取代.它更清洁,更容易使用.
public IHttpActionResult Get()
{
Object obj = new Object();
if (obj == null)
return NotFound();
return Ok(obj);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以封装以创建自定义的. 使用IHttpActionResult时如何设置自定义标题?
我还没有找到实现自定义结果的需求,但是当我这样做时,我将会走这条路.
它可能非常类似于使用旧的.
进一步扩展这一点并提供更多信息.您还可以包含包含某些请求的消息.例如.
return BadRequest("Custom Message Here");
Run Code Online (Sandbox Code Playgroud)
您不能与许多其他的一起执行此操作,但有助于您要发回的常见消息.
您可以返回错误响应以提供更多详细信息。
public HttpResponseMessage Get()
{
HttpError myCustomError = new HttpError("The file has no content or rows to process.") { { "CustomErrorCode", 42 } };
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError);
}
Run Code Online (Sandbox Code Playgroud)
将返回:
{
"Message": "The file has no content or rows to process.",
"CustomErrorCode": 42
}
Run Code Online (Sandbox Code Playgroud)
此处有更多详细信息:http : //blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
我还使用http://en.wikipedia.org/wiki/List_of_HTTP_status_codes帮助我确定要返回的http状态代码。
| 归档时间: |
|
| 查看次数: |
82181 次 |
| 最近记录: |