2

我在我的 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?

4

1 回答 1

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)
于 2013-06-06T08:23:53.790 回答