gpt4 book ai didi

asp.net-mvc - 路由约束不适用于 ASP.NET MVC

转载 作者:行者123 更新时间:2023-12-02 03:36:58 25 4
gpt4 key购买 nike

为什么路由 http://localhost:2222/2012-adidas-spring-classic/37 不会从下面的路由匹配中获取?我收到 404 错误。

      public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" });
routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" });

#region API

routes.MapRouteLowercase(
"NamedHomeEvent",
"{year}-{name}/{Id}",
new { controller = "Event", action = "Index", year = DateTime.Now.Year },
new { year = @"\d{4}", Id = @"\d+" }
);



public virtual ActionResult Index(int? id, int? year, string name)
{

最佳答案

路由引擎在此无法为您提供帮助。您可以编写自定义路由来处理这种情况:

public class MyRoute : Route
{
public MyRoute()
: base(
"{year-name}/{id}",
new RouteValueDictionary(new { controller = "Event", action = "Index", id = UrlParameter.Optional }),
new RouteValueDictionary(new { id = @"\d*" }),
new MvcRouteHandler()
)
{
}

public override RouteData GetRouteData(HttpContextBase httpContext)
{
var routeData = base.GetRouteData(httpContext);
if (routeData == null)
{
return null;
}

var yearName = (string)routeData.Values["year-name"];
if (string.IsNullOrWhiteSpace(yearName))
{
return null;
}

var parts = yearName.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
return null;
}

var year = parts.First();
int yearValue;
if (!int.TryParse(year, out yearValue))
{
return null;
}

var name = parts.Last();

routeData.Values.Add("year", year);
routeData.Values.Add("name", name);

return routeData;
}
}

然后注册此路由:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" });
routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" });

routes.Add("NamedHomeEvent", new MyRoute());
}

关于asp.net-mvc - 路由约束不适用于 ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com