gpt4 book ai didi

asp.net-mvc - ASP.NET MVC SEO 友好 URL

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:36:43 25 4
gpt4 key购买 nike

我正在尝试关注此页面 http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx这就是我在 global.asax 中的内容,

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"MemberRoute", // routeName
"member/{userId}/{pseudoName}", // url
new
{ // url defaults
controller = "Member",
action = "Index",
userId = 0,
pseudoName = UrlParameter.Optional
},
new
{ // url constraints
userId = @"\d+" // must match url {userId}
}
);
}

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}

成员 Controller ,

public ActionResult Index(int id, string pseudoName)
{
User user;
var unitOfWork = new UnitOfWork();
user = unitOfWork.UserRepository.GetById(id);

var expectedName = user.PseudoName.ToSeoUrl();
var actualName = (pseudoName ?? "").ToLower();

// permanently redirect to the correct URL
if (expectedName != actualName)
return RedirectToActionPermanent("Index", "Member", new { id = user.UserId, pseudoName = expectedName });
return View(user);
}

这是从 AccountController 的登录操作返回的,

return RedirectToAction("Index", "Member", new { id = user.UserId, pseudoName = user.PseudoName });

当发生重定向时,Url 最终看起来像 http://site.com/Member/1?pseudoName=CEO

我做错了什么?

最佳答案

请记住,您是在 MapHttpRoute 上使用 MapRoute,因此您想使用 RedirectToRoute 或(在标记中)@Html.RouteLink

因此,要使其在上面的代码中工作,而不是重定向到一个操作,然后指定参数,请使用以下代码:

return RedirectToRoute("Member", new {
userId = user.Id, // note i use userId as it's in the route's url
pseudoName = user.pseudoName
});

此外,您的路线修复如下:

routes.MapRoute(
"Member", // routeName
"member/{userId}/{pseudoName}", // url
new { // url defaults
controller = "Member",
action = "Index",
userId = 0,
pseudoName = UrlParameter.Optional
},
new { // url constraints
userId = @"\d+" // must match url {userId}
}
);

关于asp.net-mvc - ASP.NET MVC SEO 友好 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11173194/

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