ASP.NET Web API PUT with catch-all route

ぃ、小莉子 提交于 2020-01-24 17:17:04

问题


With the new web api, is it possible to use a catch all route like

routes.MapHttpRoute(
   name: "name",
   routeTemplate: "api/{*id}",
   defaults: new { controller = "mycontroller", id = RouteParameter.Optional}
);

with the PUT method? Typically the PUT method is used like

public HttpResponseMessage Put(string id, string body)
{
    ...
}

where body is the body of the PUT request. However with a catch all route, this doesn't appear to work and I'm receiving the error

{
    "ExceptionType":"System.ArgumentException",
    "Message":":"No 'MediaTypeFormatter' is available to read an object of type 'String' with the media type ''undefined''.",
    "StackTrace":"..."
}

where my put method looks like

public HttpResponseMessage Put(string id)
{
    ...
}

I figure I should be able to use the catch all route, where the route information will be passed to the id parameter, and that I should be able to access the body from the response object. Any ideas?


回答1:


I don't think the route is the problem. You should be fine with that route if that's how you want to write it. You will get that error if you do not have an appropriate MediaTypeFormatter for the Content-Type you are sending in the request. For example, if you are using a JsonMediaTypeFormatter you need to make sure you are sending

Content-Type: application/json

in your request. Which it doesn't look like you are.



来源:https://stackoverflow.com/questions/10059304/asp-net-web-api-put-with-catch-all-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!