c# - MVC : How to manage slahses in URL int the first route parameter

标签 c# .net asp.net-mvc asp.net-mvc-routing

我需要在我的 ASP MVC 应用程序中将两个可能包含斜杠的变量映射到 Controller 。让我们看一个例子。

enter image description here

  • Repository 和 Path 将是 URL 编码的参数。
  • 存储库最多可以有 0 个斜杠或 1 个斜杠(rep 或 rep/module)
  • 路径可以有任意数量的斜杠。

例如,这些是有效的 URL:

http://mysite/rep/Items
http://mysite/rep/module/Items/foo/bar/file.c

有人可以就如何定义这条路线提出一些建议吗?

最佳答案

看起来自定义路线可能会削减芥末:

public class MyRoute: Route
{
    public MyRoute()
        : base("{*catchall}", new MvcRouteHandler())
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            // we do not have a match for {*catchall}, although this is very
            // unlikely to ever happen :-)
            return null;
        }

        var segments = httpContext.Request.Url.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
        if (segments.Length < 4)
        {
            // we do not have the minimum number of segments
            // in the url to have a match
            return null;
        }

        if (!string.Equals("items", segments[1], StringComparison.InvariantCultureIgnoreCase) &&
            !string.Equals("items", segments[2], StringComparison.InvariantCultureIgnoreCase))
        {
            // we couldn't find "items" at the expected position in the url
            return null;
        }

        // at this stage we know that we have a match and can start processing

        // Feel free to find a faster and more readable split here
        string repository = string.Join("/", segments.TakeWhile(segment => !string.Equals("items", segment, StringComparison.InvariantCultureIgnoreCase)));
        string path = string.Join("/", segments.Reverse().TakeWhile(segment => !string.Equals("items", segment, StringComparison.InvariantCultureIgnoreCase)).Reverse());

        rd.Values["controller"] = "items";
        rd.Values["action"] = "index";
        rd.Values["repository"] = repository;
        rd.Values["path"] = path;
        return rd;
    }
}

可以在标准路由之前注册:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add("myRoute", new MyRoute());

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

如果您打算在 url 的路径部分中放置任意字符串,我希望您知道 Zombie Operating Systems这可能会让您大吃一惊。

关于c# - MVC : How to manage slahses in URL int the first route parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24932519/

相关文章:

.net - 如何将可空类型转换为其基础类型?

c# - 使用 Silverlight 应用程序支持插件的最佳方式是什么?

asp.net-mvc - Asp Net MVC 与 VM 这是一个好的实践吗? (代码示例)

asp.net-mvc - ASP.Net : Do I need to add javascript source of _ValidationScriptsPartial. cshtml 到 _layout.cshtml?

c# - 在以下路径找不到布局页 "~/Views/Shared/"

c# - 从 Image 实例中获取原始数据

c# - PrintDocument 是将整个文档发送到打印机还是逐行发送?

c# - 从 ListView 控件获取索引项

c# - 字符串如何在 C# 中终止?

.net - 如何向某人解释不同的 .NET 版本?