如何使用自定义的约束,在ASP.NET MVC路由一个HttpMethodConstraint? [英] How do I use a custom constraint with a HttpMethodConstraint in ASP.NET MVC routing?
问题描述
我有一个控制器,只接受POST这个网址:
I have a controller that only accepts a POST on this URL:
POST http://server/stores/123/products
应将有关内容类型应用程序/ JSON
的,所以这是我在我的路由表:
The POST should be of content-type application/json
, so this is what I have in my routing table:
routes.MapRoute(null,
"stores/{storeId}/products",
new { controller = "Store", action = "Save" },
new {
httpMethod = new HttpMethodConstraint("POST"),
json = new JsonConstraint()
}
);
其中, JsonConstraint
是:
public class JsonConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.ContentType == "application/json";
}
}
当我使用的路线,我得到一个405禁止访问:
When I use the route, I get a 405 Forbidden:
用于访问路径/存储/ 123 /产品'是不允许的HTTP动词POST
不过,如果我删除 JSON =新JsonConstraint()
约束,它工作正常。有谁知道我做错了吗?
However, if I remove the json = new JsonConstraint()
constraint, it works fine. Does anybody know what I'm doing wrong?
推荐答案
我把这个注释,但没有足够的空间。
I'd put this in a comment but there isn't enough space.
在编写自定义约束它要检查 routeDirection
参数,并确保你的逻辑只运行在正确的时间非常重要。
When writing a custom constraint it is very important to inspect the routeDirection
parameter and make sure that your logic runs only at the right time.
这参数告诉你你的约束是否正在运行,而处理传入的请求或被运行,而有人正在生成一个URL(例如,当他们叫 Html.ActionLink
)
That parameter tells you whether your constraint is being run while processing an incoming request or being run while someone is generating a URL (such as when they call Html.ActionLink
).
在你的情况我想你想要把所有的匹配code在一个巨大的如果:
In your case I think you want to put all your matching code in a giant "if":
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest) {
// Only check the content type for incoming requests
return httpContext.Request.ContentType == mimeType;
}
else {
// Always match when generating URLs
return true;
}
}
这篇关于如何使用自定义的约束,在ASP.NET MVC路由一个HttpMethodConstraint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!