ASP.NET Web API PUT with catch-all route

2019-07-18 21:36发布

问题:

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.