2019-07-22 13:52

C# 用 Lambda 設定 MVC Route Constraint

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


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

  1. public class ValueConstraint : IRouteConstraint 
  2. { 
  3.    private Func<string, bool> _match; 
  4.  
  5.    public ValueConstraint(Func<string, bool> match) 
  6.    { 
  7.        _match = match; 
  8.    } 
  9.  
  10.    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
  11.    { 
  12.        return _match("" + values[parameterName]); 
  13.    } 
  14. } 


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

  1. public class HttpConstraint : IRouteConstraint 
  2. { 
  3.    private Func<HttpContextBase, bool> _match; 
  4.  
  5.    public HttpConstraint(Func<HttpContextBase, bool> match) 
  6.    { 
  7.        _match = match; 
  8.    } 
  9.  
  10.    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
  11.    { 
  12.        return _match(httpContext); 
  13.    } 
  14. } 

0 回應: