忽略ASP.NET MVC核心路由中的第一个段

时间:2018-02-27 15:33:07

标签: asp.net-mvc routes .net-core url-routing asp.net-mvc-routing

我正在寻找能够匹配以下路线的路线定义:

  • /segment/xxxx/def
  • /segment/.../xxxx/def
  • /segment/that/can/span/xxxx/def

并且能够使用param`def。

运行动作xxxx

但是这种路线是不允许的:

[Route("/{*segment}/xxx/{myparam}")]

怎么做?

1 个答案:

答案 0 :(得分:3)

您可以将自定义IRouter与正则表达式结合使用,以执行此类高级网址匹配。

public class EndsWithRoute : IRouter
{
    private readonly Regex urlPattern;
    private readonly string controllerName;
    private readonly string actionName;
    private readonly string parameterName;
    private readonly IRouter handler;

    public EndsWithRoute(string controllerName, string actionName, string parameterName, IRouter handler)
    {
        if (string.IsNullOrWhiteSpace(controllerName))
            throw new ArgumentException($"'{nameof(controllerName)}' is required.");
        if (string.IsNullOrWhiteSpace(actionName))
            throw new ArgumentException($"'{nameof(actionName)}' is required.");
        if (string.IsNullOrWhiteSpace(parameterName))
            throw new ArgumentException($"'{nameof(parameterName)}' is required.");
        this.controllerName = controllerName;
        this.actionName = actionName;
        this.parameterName = parameterName;
        this.handler = handler ??
            throw new ArgumentNullException(nameof(handler));
        this.urlPattern = new Regex($"{actionName}/[^/]+/?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    }

    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        var controller = context.Values.GetValueOrDefault("controller") as string;
        var action = context.Values.GetValueOrDefault("action") as string;
        var param = context.Values.GetValueOrDefault(parameterName) as string;

        if (controller == controllerName && action == actionName && !string.IsNullOrEmpty(param))
        {
            return new VirtualPathData(this, $"{actionName}/{param}".ToLowerInvariant());
        }
        return null;
    }

    public async Task RouteAsync(RouteContext context)
    {
        var path = context.HttpContext.Request.Path.ToString();

        // Check if the URL pattern matches
        if (!urlPattern.IsMatch(path, 1))
            return;

        // Get the value of the last segment
        var param = path.Split('/').Last();

        //Invoke MVC controller/action
        var routeData = context.RouteData;

        routeData.Values["controller"] = controllerName;
        routeData.Values["action"] = actionName;
        // Putting the myParam value into route values makes it
        // available to the model binder and to action method parameters.
        routeData.Values[parameterName] = param;

        await handler.RouteAsync(context);
    }
}

用法

app.UseMvc(routes =>
{
    routes.Routes.Add(new EndsWithRoute(
        controllerName: "Home", 
        actionName: "About", 
        parameterName: "myParam", 
        handler: routes.DefaultHandler));

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

此路由已参数化,允许您传入与被调用的操作方法对应的控制器,操作和参数名称。

public class HomeController : Controller
{
    public IActionResult About(string myParam)
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }
}

要使其与任何操作方法名称匹配并能够使用该操作方法名称再次构建URL,还需要做一些工作。但是这条路线允许您通过多次注册来添加其他动作名称。

  

注意:对于搜索引擎优化目的,将相同内容放在多个网址上通常不被视为一种良好做法。如果您这样做,建议使用canonical tag通知搜索引擎哪些网址是权威

See this to accomplish the same in ASP.NET MVC (prior to ASP.NET Core)