如何强制Web API 2媒体类型格式化程序中的Content-Type
本文关键字:程序 格式化 Content-Type 类型 媒体 何强制 Web API | 更新日期: 2023-09-27 18:20:27
我的MediaTypeFormatter有问题。当我在Accept标头设置为"application/vnd.siren+json"的情况下发出请求时,它会正确地将响应设置为Content-Type标头设置为"application/vnd.serin+json"。
我想做的是,即使我没有明确表示我想要"application/vnd.serine+json",我也希望将响应内容类型设置为"application/vdn.serine+json"。
例如,一个沼泽标准调用将设置Accept标头:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
当我使用Accept头执行GET时,我的响应类型将是application/xml,而不是application/vnd.serine+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();
}
});
}
我已尝试使用内容更新上下文的值。Headers.ContentType=新的MediaTypeHeaderValue(_mediaType);然而1)。它不起作用,内容类型仍然设置为application/xml和2)。我担心在这样的WriteAsynch方法中使用Context。
如何强制我的响应标头类型(而不在控制器中明确设置它)。
正如您在问题中提到的那样,在调用WriteToStreamAsync
时编写标题已经太晚了。相反,您需要覆盖SetDefaultContentHeaders
。
从文件来看,这是:
设置将使用此格式化程序进行格式化的内容的默认标头。
要更改内容类型,您可以通过自己的MediaTypeHeaderValue
传递到基本方法:
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, new MediaTypeHeaderValue(_mediaType));
}