2014-09-03 91 views
1

我的MediaTypeFormatter出现问题。当我将Accept头设置为“application/vnd.siren + json”时,它会正确设置将Content Type头设置为“application/vnd.siren + json”的响应。如何从Web API强制使用Content-Type 2 MediaTypeFormatter

我想要做的是甚至当我没有明确说明我想要“application/vnd.siren + json”时,我想将响应内容类型设置为“application/vnd.siren + json ”。

例如,沼泽标准通话都会有这个接受报头组:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 

当我使用接受头一个GET,我的反应类型为应用程序/ XML,而不是应用程序/越南盾。警笛+ JSON。

WebApiConfig.cs已被配置为:

SirenMediaTypeFormatter sirenMediaTypeFormatter = new SirenMediaTypeFormatter(); 
sirenMediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); 
sirenMediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.siren+json")); 
config.Formatters.Insert(0, sirenMediaTypeFormatter); 

我已经建立了我的MediaTypeFormatter为:

public class SirenMediaTypeFormatter : JsonMediaTypeFormatter 
{ 
    private static Type _supportedType = typeof(Entity); 
    private const string _mediaType = "application/vnd.siren+json"; 

    public SirenMediaTypeFormatter() 
    { 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue(_mediaType)); 
    } 

    public override bool CanReadType(Type type) 
    { 
     return type == _supportedType; 
    } 

    public override bool CanWriteType(Type type) 
    { 
     bool blnRetval = (typeof(Entity).IsAssignableFrom(type)); 
     return blnRetval; 
    } 


    public override Task WriteToStreamAsync(Type type, object value, 
    Stream stream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) 
    { 
     return Task.Factory.StartNew(() => 
     { 
      if (typeof(Entity).IsAssignableFrom(type)) 
      { 
       content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType); 

       var objectToSerialize = BuildSirenDocument(value, stream, content.Headers.ContentType.MediaType); 


       var jsonSerializerSettings = new JsonSerializerSettings 
       { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
       }; 

       string jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(objectToSerialize, jsonSerializerSettings); 

       StreamWriter writer = new StreamWriter(stream); 
       writer.Write(jsonResult); 
       writer.Flush(); 

      } 
     }); 
    } 

我尝试更新使用content.Headers.ContentType背景下的价值= new MediaTypeHeaderValue(_mediaType);然而1)。它不起作用,内容类型仍然设置为application/xml和2)。我担心在像这样的WriteAsynch方法中使用Context进行游戏。

我该如何去强制我的响应头类型(没有明确地在控制器中设置它)。

回答

2

到时候写下标题为时已经太晚了WriteToStreamAsync被调用,因为您提到了您的问题。相反,您需要覆盖SetDefaultContentHeaders

从文档,这样的:

设置,将使用该格式进行格式化内容的默认头。

要改变,你可以通过自己的MediaTypeHeaderValue传递给基方法的内容类型:

public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) 
{ 
    base.SetDefaultContentHeaders(type, headers, new MediaTypeHeaderValue(_mediaType)); 
} 
+0

辉煌!这工作完美。我一直在努力争取一段时间,很好的解决办法。 – ShaunP 2014-09-04 10:41:24

相关问题