【问题标题】:MVC Routing - wildcard URL, but constrainedMVC 路由 - 通配符 URL,但受限制
【发布时间】:2019-12-09 07:16:02
【问题描述】:

我基本上想这样做:

routes.MapRoute(
  "Pass-through",
  "/api/{*url}",
  new { controller = "PassThrough", action = "PassThroughToApi" });

我将请求发送到的控制器有:

public ContentResult PassThroughToApi(string url = null)

但是,我希望能够同时限制 URL。如:

routes.MapRoute(
  "Pass-through",
  "/api/v1/some/specific/address/{whatever}/{parameters}",
  new { controller = "PassThrough", action = "PassThroughToApi" });

但我仍然希望控制器将请求的 URL 作为变量获取,并且我不关心获取实际参数,只要 URL 与模式匹配即可。还是我应该从其他地方(例如上下文)获取请求的 URL,而不是作为参数传递给它?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing


    【解决方案1】:

    您可以创建custom route constraint

    public class ApiRedirectingConstraint : IRouteConstraint
    {
        private string _matchUrl;
    
        public ApiRedirectingConstraint(string matchUrl)
        {
            _matchUrl = matchUrl;
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            string url = (string)values["url"];
    
            bool isMatch = true;
            //check url for specific match with _matchUrl
    
            return isMatch;
        }
    }
    

    并将其分配给Pass-through 路由

    routes.MapRoute(
        "Pass-through",
        "/api/{*url}",
        new { controller = "PassThrough", action = "PassThroughToApi" },
        new { apiRedirect = new ApiRedirectingConstraint("/api/v1/some/specific/address/{whatever}/{parameters}") }
    );
    

    【讨论】:

    • 我需要能够在路由引导程序中指定路由(约束),例如在routes.MapRoute。我想知道,也许如果我将实际的约束 URL 作为参数传递给 ApiRedirectingConstraint ctor
    • @HristoYankov 有帮助吗?或者你可能需要别的东西?
    猜你喜欢
    • 1970-01-01
    • 2015-06-22
    • 2014-12-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2022-09-23
    相关资源
    最近更新 更多