何时使用HttpResponseMessage和Request.CreateResponse [英] When to use HttpResponseMessage and Request.CreateResponse

查看:56
本文介绍了何时使用HttpResponseMessage和Request.CreateResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候应该使用HttpResponseMessage对象,什么时候应该使用Request.CreateResponse(...)方法?

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

HttpResponseMessage对象和Request.CreateResponse(...)方法之间有什么区别?

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

推荐答案

HttpResponseMessage对象和 Request.CreateResponse(...)方法?

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

这很明显,但是Request.CreateResponse是用于创建HttpResponseMessage对象的辅助方法.

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

何时必须使用HttpResponseMessage对象以及何时必须使用HttpResponseMessage对象 Request.CreateResponse(...)方法?

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

如果要使用内置的内容协商功能,请使用Request.CreateResponse.返回对象时,ASP.NET Web API必须将对象序列化为响应主体.通常可以是JSON或XML(其他媒体类型也可以,但是您需要创建格式化程序).选择的媒体类型(JSON或XML)基于请求的内容类型,请求中的Accept标头等,并且内容协商是确定要使用的媒体类型的过程.通过使用Request.CreateResponse,您将自动使用此过程的结果.

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.

另一方面,如果您自己创建HttpResponseMessage,则必须指定一个媒体格式化程序,基于该格式将对对象进行序列化,并且通过自己指定媒体格式化程序,您可以覆盖conneg的结果.

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.

编辑 这是有关如何指定JSON格式程序的示例.

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)
    };
}

这样,即使您使用Accept:application/xml发送请求,您也只会获得JSON.

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

这篇关于何时使用HttpResponseMessage和Request.CreateResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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