Put content in HttpResponseMessage object?

后端 未结 8 1482
感情败类
感情败类 2020-11-28 03:31

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message

相关标签:
8条回答
  • 2020-11-28 03:44

    Apparently the new way to do it is detailed here:

    http://aspnetwebstack.codeplex.com/discussions/350492

    To quote Henrik,

    HttpResponseMessage response = new HttpResponseMessage();
    
    response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");
    

    So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object.

    0 讨论(0)
  • 2020-11-28 03:46

    You should create the response using Request.CreateResponse:

    HttpResponseMessage response =  Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
    

    You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header. This saves you from manually choosing a formatter.

    0 讨论(0)
  • 2020-11-28 03:47

    No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

    product = await response.Content.ReadAsAsync<Product>();
    

    Could be replaced with:

    response.Content = new StringContent(string product);
    
    0 讨论(0)
  • 2020-11-28 03:52

    For a string specifically, the quickest way is to use the StringContent constructor

    response.Content = new StringContent("Your response text");
    

    There are a number of additional HttpContent class descendants for other common scenarios.

    0 讨论(0)
  • 2020-11-28 03:55

    Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...

            return new System.Web.Http.Results.ResponseMessageResult(
                new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
                });
    

    See nashawn's answer for JsonContent.

    0 讨论(0)
  • 2020-11-28 03:57

    The easiest single-line solution is to use

    return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };
    

    For serialized JSON content:

    return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };
    
    0 讨论(0)
提交回复
热议问题