【问题标题】:How do I set the response format to the same format as the request?如何将响应格式设置为与请求相同的格式?
【发布时间】:2013-02-04 19:34:45
【问题描述】:

我创建了一个自定义调度程序来处理使用客户媒体类型的版本控制。它看起来像这样:

application/vnd.mycompany.myapi-v1+json

为了选择正确的控制器而提取版本号已全部启动并正常工作,但作为 MVC 的新手,我不确定如何设置响应格式。我们要做的是设置响应格式以匹配请求。所以在这个例子中,响应将是 json。现在我假设我将不得不从这个内容类型中提取它,这很好,但是有人可以给我一个例子,说明我如何在 MVC4 中设置这个请求的响应格式,假设我已经创建了将将格式提取为字符串?

private string GetResponseFormat(){
   //some shennanigans here
}

附:不让客户端在请求期间使用接受标头的原因是已经有客户端在使用我们的旧服务,这将设置接受标头以匹配请求。

【问题讨论】:

    标签: asp.net .net asp.net-mvc-4


    【解决方案1】:

    您也可以使用Content 方法返回自定义响应类型:

    string responseType = GetResponseFormat();
    ...
    switch(responseType){
        case "json":
            string json = "yourJSON";
            return Content(json, "application/json");
        case "xml":
            string xml = "yourXML";
            return Content(xml, "text/xml");
        default:
            string plaintxt = "yourPlaintext";
            return Content(plaintxt, "text/plain"):
    }
    

    【讨论】:

      【解决方案2】:

      我能够清除现有的 Accept 标头并添加到其中:

      private void SetResponseFormatToRequestFormat(HttpRequestMessage request)
      {
          // figure out what the request format was
          _contentTypeHeader = request.Content.Headers.ContentType.ToString();
          if(_contentTypeHeader.Contains("xml")) _contentType = "application/xml";
          if (_contentTypeHeader.Contains("json")) _contentType = "application/json";
      
          // set response format to the same as the request format
          request.Headers.Accept.Clear();
          request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_contentType));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 2021-12-08
        • 1970-01-01
        • 2015-03-22
        • 2019-08-10
        • 2021-01-27
        • 1970-01-01
        相关资源
        最近更新 更多