Different return types for ASP.NET Web API

前端 未结 1 1873
孤独总比滥情好
孤独总比滥情好 2021-02-02 02:06

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

The current challenge I have is to return different return types (entity-body)

相关标签:
1条回答
  • 2021-02-02 02:59

    I derived the clean answer to this question from an answer I received on this other question.

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

    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.

    Oversimplified example:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题