gpt4 book ai didi

asp.net-mvc - 如何使 MVC 路由处理带有破折号的 url

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

我在 MVC 中定义了一条路由,如下所示:

routes.MapRoute(
name: "ContentNavigation",
url: "{viewType}/{category}-{subCategory}",
defaults: new { controller = "Home", action = "GetMenuAndContent", viewType = String.Empty, category = String.Empty, subCategory = String.Empty });

如果我导航到http://example.com/something/category-and-this-is-a-subcategory

它将变量填充为:

viewType: "something"
category: "category-and-this-is-a"
subCategory: "subcategory".

我想要的是第一个破折号之前的单词始终进入类别,其余的进入子类别。所以它会产生:

viewType: "something"
category: "category"
subCategory: "and-this-is-a-subcategory"

我怎样才能实现这个目标?

最佳答案

一种可能性是编写自定义路由来处理路由段的正确解析:

public class MyRoute : Route
{
public MyRoute()
: base(
"{viewType}/{*catchAll}",
new RouteValueDictionary(new
{
controller = "Home",
action = "GetMenuAndContent",
}),
new MvcRouteHandler()
)
{
}

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

var catchAll = rd.Values["catchAll"] as string;
if (!string.IsNullOrEmpty(catchAll))
{
var parts = catchAll.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
rd.Values["category"] = parts[0];
rd.Values["subCategory"] = parts[1];
return rd;
}
}

return null;
}
}

您将这样注册:

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

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

...
}

现在假设客户端请求 /something/category-and-this-is-a-subcategory,那么将调用以下 Controller 操作:

public class HomeController : Controller
{
public ActionResult GetMenuAndContent(string viewType, string category, string subCategory)
{
// viewType = "something"
// category = "category"
// subCategory = "and-this-is-a-subcategory"

...
}
}

关于asp.net-mvc - 如何使 MVC 路由处理带有破折号的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582743/

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