问题
Here is the routing configuration in WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApiPut",
routeTemplate: "api/{controller}",
defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Post, HttpMethod.Delete) }
);
Here is my controller:
public class MyController : ApiController {
[HttpPut]
public void Put()
{
//blah
}
}
Somehow when the client sents the PUT request with the URL /api/myController/12345
, it still maps to the Put
method in MyController
, I am expecting an error like resource not found.
How to force the Put
method only accept the request without a parameter?
Thanks in advance!
回答1:
You're putting your httpMethod
constraint into defaults
, but it should be in constraints
.
defaults
just says what the default values will be if the request doesn't include some or all of them as routing parameters (which in the case of the verb, is meaningless, since every HTTP request always has a verb as part of the protocol). constraints
limit the combination of route values that will activate the route, which is what you're actually trying to do.
FYI, for this simple/standard routing, you don't need the [HttpPut]
attribute in an API controller either. That's already handled by the HTTP routing which maps the verb to the controller method.
回答2:
This works to constrain http method on routes:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "LocationApiPOST",
routeTemplate: "api/{orgname}/{fleetname}/vehicle/location",
defaults: new { controller = "location" }
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);
config.Routes.MapHttpRoute(
name: "LocationApiGET",
routeTemplate: "api/{orgname}/{fleetname}/{vehiclename}/location/{start}",
defaults: new { controller = "location", start = RouteParameter.Optional }
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
...
}
来源:https://stackoverflow.com/questions/12609759/how-to-define-the-put-method-in-routing-only-limit-to-the-put-methods-in-control