首页 文章

如何检查和更改Web API请求Content-Type标头?

提问于
浏览
-1

我的ASP.NET Web API中有一个 POST 方法,该方法将由无法发送 Content-Type 标头的客户端使用 . 我想检查Request的 Content-Type 标头,如果它为null,我想将它设置为 application/x-www-form-urlencode .

我该如何实现这一目标?

附:如果请求没有 Content-Type: application/x-www-form-urlencode ,我得到:

请求包含实体主体但没有Content-Type标头 . 此资源不支持推断的媒体类型'application / octet-stream' . 没有MediaTypeFormatter可用于从媒体类型为'application / octet-stream'.System.Net.Http的内容中读取类型为'CustomerModel'的对象 . System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent内容,类型类型,IEnumerable1格式化程序,System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)中的UnsupportedMediaTypeException System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync上的IFormatterLogger formatterLogger,CancellationToken cancellationToken)(HttpRequestMessage请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)

1 回答

  • 0

    如果请求没有Content-Type标头,那么它将被设置为 application/octet-stream

    HTTP / 1.1 RFC 2616规范的Section 7.2.1说明了有关实体主体类型的信息:

    当实体主体包含在消息中时,该主体的数据类型通过 Headers 字段Content-Type和Content-Encoding确定 . 这些定义了一个两层有序编码模型:entity-body:= Content-Encoding(Content-Type(data))Content-Type指定底层数据的媒体类型 . 内容编码可用于指示应用于数据的任何附加内容编码,通常用于数据压缩的目的,其是所请求资源的属性 . 没有默认编码 . 包含实体主体的任何HTTP / 1.1消息应该包括定义该主体的媒体类型的Content-Type头部字段 . 当且仅当媒体类型不是由Content-Type字段给出时,接收者可以尝试通过检查其内容和/或用于标识资源的URI的名称扩展来猜测媒体类型 . 如果媒体类型仍然未知,则收件人应该将其视为“application / octet-stream”类型 .

    尝试先清除所有格式化程序,然后只添加你需要的格式化程序

    config.Formatters.Clear();
    config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());
    

相关问题