不同的返回类型的ASP.NET Web API [英] Different return types for ASP.NET Web API

查看:137
本文介绍了不同的返回类型的ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用ASP.NET MVC 4网页API通过HTTP来写真正REST Web服务。

I am attempting to write truly RESTful web services over HTTP using ASP.NET MVC 4 Web API.

目前的挑战,我必须要返回根据我的状态code不同的返回类型(实体主体)。

The current challenge I have is to return different return types (entity-body) based upon my status code.

例如,对于资源锤我有一个.NET模型类豪迈,和HammerController:

For example, for resource Hammer I have a .NET model class "Hammer", and a HammerController:

namespace Awesomeness
{
    public class HammerController : ApiController
    {
        public Hammer Get(int id)
        {
        }
...

如果该ID不存在(404)或需要不同的授权(401),我可以轻松快捷的回报,并手动设置状态code和任何其他内容,这是很酷。然而,在许多非2xx状态,我想返回不同的实体主体比锤资源再presentation。我可以很容易地手动做到这一点,但我想这取决于请求头,以利用ASP​​.NET MVC 4的Web API AUTOMAGIC序列化和反序列化到/从XML或JSON。

If the ID doesn't exist (404) or requires different authorization (401), I can easily shortcut the return and manually set the status code and any other content, which is cool. However, in many non-2xx statuses, I want to return a different entity-body than the Hammer resource representation. I can easily do this manually, but I'd like to take advantage of the ASP.NET MVC 4 Web API automagic serialization and deserialization to/from XML or JSON depending on the request headers.

所以我的核心问题是:我可以拿ASP.NET MVC 4的Web API的AUTOMAGIC系列化优势,同时返回不同的返回类型

我曾经想过一些潜在的方法是:

Some potential approaches I have thought about are:


  1. 有控制器方法返回的主要资源类型,但是短路与 HttpContext.Current.Response 并以某种方式挂接到AUTOMAGIC序列化($返回p $ pferred)。

  1. Have the controller method return the main resource type, but short-circuit the return with HttpContext.Current.Response and somehow hook into the automagic serialization (preferred).

有我的模型类更像一个C工会的地方重新presents这种类型或类型,让它系列化的正常返回过程的一部分(而且只重载状态code和任何响应头需要)。即使我想通过如何做到这一点,我有一种感觉,它仍然将结束是非常哈克。

Have my Model class be more like a C union where it represents this type or that type and let it get serialized as part of the normal return process (and just override status code and any response headers needed). Even if I think through how to do this, I have a feeling it would still end up being very hacky.

主编2012年4月27日:我可以抛出的Htt presponseException是这样的:

Edited Apr 27 2012: I can throw an HttpResponseException like this:

HttpResponseMessage response = new HttpResponseMessage(statusCode);
if (!string.IsNullOrWhiteSpace(text))
{
    response.Content = new StringContent(text);
}
throw new HttpResponseException(response);

...但现在我需要弄清楚如何挂钩到自动魔法序列并设置 response.Content 接受头重新协商presentation。

...but now I need to figure out how to hook into the auto-magic serialization and set the response.Content to the Accept header negotiated representation.

推荐答案

我来源于我对<接收答案干净这个问题的答案href=\"http://stackoverflow.com/questions/10357526/cant-get-asp-net-mvc-4-web-api-to-return-status-$c$c-201-created-for-succes\">this另一个问题。

如果我让我返回值的Htt presponseMessage ,我可以通过返回是新的Htt返回我需要的任何状态或内容presponseMessage()

If I make my return value HttpResponseMessage, I can return whatever status or content I need to by returning either a new HttpResponseMessage().

修改2012/5/10 :感谢来自@DarrelMiller,德precated 的Htt presponseMessage&LT删除输入; T&GT; 并调用的Htt prequestMessage.CreateResponse&LT更换; T&GT;()扩展方法。注:此扩展方法不可用在MVC4 /的WebAPI测试版。您需要<一个href=\"http://blogs.msdn.com/b/henrikn/archive/2012/04/09/getting-started-with-asp-net-web-stack-source-on-$c$cplex.aspx\">build从源头或获得<一个href=\"http://blogs.msdn.com/b/henrikn/archive/2012/04/29/using-nightly-nuget-packages-with-asp-net-web-stack.aspx\">nightly建立。

EDIT 5/10/2012: Thanks to input from @DarrelMiller, removed deprecated HttpResponseMessage<T> and replaced with call to HttpRequestMessage.CreateResponse<T>() extension method. NOTE: This extension method is not available in the MVC4/WebAPI beta. You need to build from source or get the nightly build.

简化的示例:

public HttpResponseMessage Post(MyResource myResource)
{
    ...
    if (goodStuff)
    {
        return ControllerContext.Request.CreateResponse(HttpStatusCode.Created, myNewResource);
    }
    else if (badStuff)
    {
        return ControllerContext.Request.CreateResponse(HttpStatusCode.BadRequest, badRequest);
    }
    else
    {
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}

这篇关于不同的返回类型的ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆