2019-07-22 13:52

C# 用 Lambda 設定 MVC Route Constraint

MVC 的 Route Constraint 支援 Regular Pattern (string) 以及 IRouteConstraint,簡單的限制還可以用 Regular 處理,複雜的就需要實作 IRouteConstraint 了,既然都是一次工,索性就想要搭配 Lambda 讓設定可以更彈性的點。


routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { controller = new ValueConstraint(x => x.ToUpper() != "WCF") }
);

public class ValueConstraint : IRouteConstraint
{
    private Func<string, bool> _match;

    public ValueConstraint(Func<string, bool> match)
    {
        _match = match;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return _match("" + values[parameterName]);
    }
}


順便增加了 HttpContextBase 的處理
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { authenticated = new HttpConstraint(x => x.Request.IsAuthenticated) }
);

public class HttpConstraint : IRouteConstraint
{
    private Func<HttpContextBase, bool> _match;

    public HttpConstraint(Func<HttpContextBase, bool> match)
    {
        _match = match;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return _match(httpContext);
    }
}

0 回應: