简体   繁体   English

REST WEB API:如何使Content-Type标头为可选?

[英]REST WEB API: How to make Content-Type header optional?

I have Web API and would like to make the content type optional. 我有Web API,并且希望使内容类型可选。

Currently if I ignored content-Type header while calling REST (POST) Method it throws error. 当前,如果我在调用REST(POST)方法时忽略了content-Type标头,则会引发错误。

This is how I defined route in Web API - 这就是我在Web API中定义路由的方式-

routes.MapHttpRoute(
   name: "myMethodPost",
   routeTemplate: "api/{id}/Settings/{settings}",
   defaults: new { controller = "Settings", action = "updateSettings" },
   constraints: new { httpMethod = new HttpMethodConstraint("POST") }
);

while calling this method - 在调用此方法时-

api/1/Settings/testSettings
method = "Post"

it throws error. 它引发错误。 but when added following - 但是当添加以下内容时-

apiRequest.ContentType = "application/json";

it is working fine. 它工作正常。

Now, how to make Content-Type header optional? 现在,如何使Content-Type标头为可选?

You could create a messagehandler on the server that will set the Content-Type to 'application/json' if it is missing and there is a non-zero length body. 您可以在服务器上创建一个消息处理程序,如果内容类型丢失并且正文长度为非零,则会将Content-Type设置为“ application / json”。 That way the client doesn't have to send it. 这样,客户端就不必发送它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Content-Type标头添加到.Net GET Web请求? - How to add the Content-Type header to a .Net GET web request? 如何从Web API 2强制使用Content-Type MediaTypeFormatter - How to force the Content-Type from a Web API 2 MediaTypeFormatter 设置Web API 2响应的内容类型 - Setting content-type for Web API 2 response 如何设置 WebClient Content-Type Header? - How to set WebClient Content-Type Header? 如果我的 Z099E7396E 中根本没有 Content-Type,ASP.NET 核心 Web API 管道的流程是什么? - What is the flow of ASP.NET Core Web API pipeline if I do not have Content-Type at all in my header? 使用带有备用内容类型的c#web api - Using c# web api with alternate content-type 如何使用Content-Type:multipart / form-data通过Web API请求主体参数访问? - How request body parameter access by Web API using Content-Type: multipart/form-data? 在.NET MVC 4(Web API)中,如何拦截控制器请求并更改其内容类型? - In .NET MVC 4 (Web API), how do I intercept a request for a controller and change it's Content-Type? 如何为 HttpClient 请求设置 Content-Type header? - How do you set the Content-Type header for an HttpClient request? 为什么在路由到 REST WebAPI 获取方法时需要内容类型 header? - Why is content-type header needed when routing to an REST WebAPI get method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM