Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

c# - When to use HttpResponseMessage and Request.CreateResponse

When should we use the HttpResponseMessage object and when should we use the Request.CreateResponse(...) method?

Also, what is the difference between the HttpResponseMessage object and the Request.CreateResponse(...) method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is difference between HttpResponseMessage object and Request.CreateResponse(...) method?

It is probably obvious but Request.CreateResponse is a helper method for creating HttpResponseMessage object.

When we must use HttpResponseMessage object and When we must use Request.CreateResponse(...) method?

If you want to use the built-in content negotiation feature, use Request.CreateResponse. When you return an object, ASP.NET Web API has to serialize the object into response body. This could be generally JSON or XML (other media types are possible but you need to create the formatter). The media type chosen (JSON or XML) is based on the request content type, Accept header in the request and so on and content negotiation is the process that determines the media type to be used. By using Request.CreateResponse, you are automatically using the result of this process.

On the other hand, if you create HttpResponseMessage yourself, you have to specify a media formatter based on which the object will be serialized and by specifying the media formatter yourself, you can override the results of conneg.

EDIT Here is an example of how to specify JSON formatter.

public HttpResponseMessage Get(int id)
{
    var foo = new Foo() { Id = id };
    return new HttpResponseMessage()
    {
        Content = new ObjectContent<Foo>(foo,
                  Configuration.Formatters.JsonFormatter)
    };
}

With this, even if you send a request with Accept:application/xml, you will only get JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...