gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:50:10 26 4
gpt4 key购买 nike

我需要在我的 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/

26 4 0