如何从ASP.NET Core MVC响应的Content-Type中删除字符集? [英] How do I remove the charset from Content-Type in a ASP.NET Core MVC response?
问题描述
无论我尝试什么,我似乎都无法从响应的Content-Type
标头中删除; charset=utf-8
部分.
No matter what I try I cannot seem to remove the ; charset=utf-8
part from my response's Content-Type
header.
[HttpGet("~/appid")]
// Doesn't work
//[Produces("application/fido.trusted-apps+json")]
public string GetAppId()
{
// Doesn't work
Response.ContentType = "application/fido.trusted-apps+json";
// Doesn't work
//Response.ContentType = null;
//Response.Headers.Add("Content-Type", "application/fido.trusted-apps+json");
return JsonConvert.SerializeObject(new
{
foo = true
});
}
我只想要application/fido.trusted-apps+json
时总是得到application/fido.trusted-apps+json; charset=utf-8
.
Note: This is to conform with the FIDO AppID and Facet Specification v1.0 for U2F which states:
响应必须将MIME内容类型设置为"application/fido.trusted-apps + json".
The response must set a MIME Content-Type of "application/fido.trusted-apps+json".
推荐答案
我采用了以下方法,在中间出路时使用中间件替换标头.看起来有点黑,必须使用这样的中间件:
I went with the following approach, using middleware to replace the header on the way out. Seems kinda hacky to have to use middleware like this:
public class AdjustHeadersMiddleware
{
private readonly RequestDelegate _next;
public AdjustHeadersMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext, CurrentContext currentContext)
{
httpContext.Response.OnStarting((state) =>
{
if(httpContext.Response.Headers.Count > 0 && httpContext.Response.Headers.ContainsKey("Content-Type"))
{
var contentType = httpContext.Response.Headers["Content-Type"].ToString();
if(contentType.StartsWith("application/fido.trusted-apps+json"))
{
httpContext.Response.Headers.Remove("Content-Type");
httpContext.Response.Headers.Append("Content-Type", "application/fido.trusted-apps+json");
}
}
return Task.FromResult(0);
}, null);
await _next.Invoke(httpContext);
}
}
Startup.cs Configure()
app.UseMiddleware<AdjustHeadersMiddleware>();
这篇关于如何从ASP.NET Core MVC响应的Content-Type中删除字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!