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

查看:20
本文介绍了何时使用 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 对象,何时必须使用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,则必须指定一个媒体格式化程序,基于该对象将被序列化,并且通过自己指定媒体格式化程序,您可以覆盖结果连接.

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天全站免登陆