C# 上载时Web API不支持的媒体类型-未传递字符集

C# 上载时Web API不支持的媒体类型-未传递字符集,c#,asp.net-web-api,http-headers,content-type,C#,Asp.net Web Api,Http Headers,Content Type,我正在开发一个新的web API,目前正在集成(重新编写)旧API以与新API配合使用。但是,我对Excel模板有问题。每次我尝试写一篇文章时,都会出现415不支持的媒体类型错误 我已设法使其工作,因此我知道我的代码很好。问题是,当我使用模板时,它会将标题中的内容类型设置为: Content-Type: application/xml; 但是,如果我将模板更改为发送: Content-Type: application/xml; charset=utf-8 正如我所期望的那样。问题是我无法在

我正在开发一个新的web API,目前正在集成(重新编写)旧API以与新API配合使用。但是,我对Excel模板有问题。每次我尝试写一篇文章时,都会出现415不支持的媒体类型错误

我已设法使其工作,因此我知道我的代码很好。问题是,当我使用模板时,它会将标题中的内容类型设置为:

Content-Type: application/xml;
但是,如果我将模板更改为发送:

Content-Type: application/xml; charset=utf-8

正如我所期望的那样。问题是我无法在生产中更改模板。我必须让我的代码与模板保持原样。

这里的问题似乎在于结尾
内容类型为:application/xml,则为code>
…Web API依赖于
System.Net.Http
库来获取请求头,此库为
HttpRequestMessage的Content.headers.ContentType
提供空值。在这种情况下,Web API会看到内容长度大于0,但没有内容类型头,因此返回
415不支持的媒体类型

遵循我已经尝试过并且有效的解决方法(我使用Owin中间件,因为这是一个可以在
System.Net.Http
库解析之前修改原始请求头的阶段…)


public void配置(IAppBuilder-appBuilder)
{
appBuilder.Use();
public class FixContentTypeHeader : OwinMiddleware
{
    public FixContentTypeHeader(OwinMiddleware next) : base(next) { }

    public override async Task Invoke(IOwinContext context)
    {
        // Check here as requests can or cannot have Content-Type header
        if(!string.IsNullOrWhiteSpace(context.Request.ContentType))
        {
            MediaTypeHeaderValue contentType;

            if(!MediaTypeHeaderValue.TryParse(context.Request.ContentType, out contentType))
            {
                context.Request.ContentType = context.Request.ContentType.TrimEnd(';');
            }
        }

        await Next.Invoke(context);
    }
}
public void Configuration(IAppBuilder appBuilder)
{
    appBuilder.Use<FixContentTypeHeader>();