[英]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.