[英]How to force the Content-Type from a Web API 2 MediaTypeFormatter
我的MediaTypeFormatter有问题。 当我在接受标头设置为“ application / vnd.siren + json”的情况下发出请求时,它正确地将响应设置为将内容类型标头设置为“ application / vnd.siren + json”。
我试图做的是即使我没有明确声明我想要“ application / vnd.siren + json”,我也想将响应内容类型设置为“ application / vnd.siren + json”。
例如,沼泽标准呼叫将设置以下“接受”标头:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
当我使用该Accept头执行GET时,我的响应类型将是application / xml而不是application / vnd.siren + 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);更新Context的值。 但是1)。 它不起作用,内容类型仍设置为application / xml和2)。 我担心像这样在WriteAsynch方法中玩弄Context。
我该如何强制我的Response标头类型(没有在控制器中显式设置)。
正如您在问题中提到的那样,在调用WriteToStreamAsync
写入标头为时已晚。 相反,您需要重写SetDefaultContentHeaders
。
从文档中,这是:
设置将使用此格式化程序格式化的内容的默认标题。
要更改内容类型,您可以将自己的MediaTypeHeaderValue
传递给基本方法:
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, new MediaTypeHeaderValue(_mediaType));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.