我在我的ASP.NET应用程序中映射了URL,如下所示:
context.MapRoute(
"Product_v1_DataExchange",
"v1/xch",
new { controller = "Data", action = "Exchange" });
context.MapRoute(
"Product_v1_Register",
"v1/register",
new { controller = "Registration", action = "Register" });
我只想关注网址:
http://servername/v1/xch
http://servername/v1/register
但是关注网址的工作正常:
http://servername/v1/xch?test
http://servername/v1/register/?*e/
http://servername/v1//./register/./?*
如何设置约束以便只允许定义的静态URL?
答案 0 :(得分:2)
像这样创建一个新的RouteConstraint
:
public class ExactMatchConstraint : IRouteConstraint
{
private readonly bool _caseSensitive;
public ExactMatchConstraint(bool caseSensitive = false)
{
this._caseSensitive = caseSensitive;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return 0 == String.Compare(route.Url.Trim('/'), httpContext.Request.RawUrl.Trim('/'), !this._caseSensitive);
}
}
然后使用它:
routes.MapRoute(
"Custom",
"My/Custom",
new { controller = "Home", action = "Custom" },
new { exact = new ExactMatchConstraint(/*true for case-sensitive */) }
);
结果:
/My/Custom (200 OK)
/My/Custom/ (200 OK)
/My/Custom/k (404 NOT FOUND)
/My/Custom/k/v (404 NOT FOUND)
/My/Custom/? (404 NOT FOUND)
/My/Custom/?k=v (404 NOT FOUND)