我的ASP.NET Web API中有一个POST
方法,该方法将由无法发送Content-Type
标头的客户端使用。
我想查看Request的Content-Type
标题,如果它为null,我想将其设置为application/x-www-form-urlencode
。
我如何实现这一目标?
P.S。如果请求没有Content-Type: application/x-www-form-urlencode
,我会得到:
请求包含实体主体但没有 Content-Type标头。推断的媒体类型 '应用程序/八位字节流'不支持此功能 resource.No MediaTypeFormatter是 可以读取类型' CustomerModel'的对象。来自内容 媒体类型 '应用程序/八位字节流' .System.Net.Http.UnsupportedMediaTypeException 在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent) content,Type type,IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable
1格式化程序,IFormatterLogger formatterLogger, 取消语音取消语言) System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage 请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken 的CancellationToken)
答案 0 :(得分:0)
如果请求没有Content-Type标头,则它将设置为application/octet-stream
Section 7.2.1说明了关于实体主体类型:
当实体主体包含在消息中时,该主体的数据类型通过标题字段Content-Type和 内容编码。这些定义了一个两层有序编码模型:
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());