我有Web API,并且希望使内容类型可选。

当前,如果我在调用REST(POST)方法时忽略了content-Type标头,则会引发错误。

这就是我在Web API中定义路由的方式-

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


在调用此方法时-

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


它引发错误。但是当添加以下内容时-

apiRequest.ContentType = "application/json";


它工作正常。

现在,如何使Content-Type标头为可选?

最佳答案

您可以在服务器上创建一个消息处理程序,如果内容类型丢失并且正文长度为非零,则会将Content-Type设置为“ application / json”。这样,客户端就不必发送它。

10-04 22:29
查看更多