When to use HttpResponseMessage and Request.CreateResponse

前端 未结 2 733
逝去的感伤
逝去的感伤 2020-12-08 02:35

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

Also, what is the differen

2条回答
  •  自闭症患者
    2020-12-08 02:52

    Request.CreateResponse(...) is just a builder, it also returns instance of HttpResponseMessage, here is the code:

    public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration)
    {
      if (request == null)
        throw Error.ArgumentNull("request");
      configuration = configuration ?? HttpRequestMessageExtensions.GetConfiguration(request);
      if (configuration == null)
        throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration, new object[0]);
      IContentNegotiator contentNegotiator = ServicesExtensions.GetContentNegotiator(configuration.Services);
      if (contentNegotiator == null)
      {
        throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoContentNegotiator, new object[1]
        {
          (object) typeof (IContentNegotiator).FullName
        });
      }
      else
      {
        IEnumerable formatters = (IEnumerable) configuration.Formatters;
        ContentNegotiationResult negotiationResult = contentNegotiator.Negotiate(typeof (T), request, formatters);
        if (negotiationResult == null)
        {
          return new HttpResponseMessage()
          {
            StatusCode = HttpStatusCode.NotAcceptable,
            RequestMessage = request
          };
        }
        else
        {
          MediaTypeHeaderValue mediaType = negotiationResult.MediaType;
          return new HttpResponseMessage()
          {
            Content = (HttpContent) new ObjectContent(value, negotiationResult.Formatter, mediaType),
            StatusCode = statusCode,
            RequestMessage = request
          };
        }
      }
    

提交回复
热议问题