asp.net-mvc - 从 Controller 更改 URL?

标签 asp.net-mvc url-routing url-parameters

有没有办法从 Controller 更改当前的 url 参数,以便在加载页面时,地址栏中会显示其他/不同的参数?

这就是我的意思,假设我有一个“产品”操作:

public ActionResult Product(int productId)
{
  ..
}

我映射了路线,以便 product/4545/purple-sunglasses映射到上面的函数,产品名称实际上被忽略了,但我想要,如果没有指定产品名称, Controller 应该添加这个,这样产品很容易进入搜索引擎等。

最佳答案

看看这里:http://www.dominicpettifer.co.uk/Blog/34/asp-net-mvc-and-clean-seo-friendly-urls

有一个很长的描述如何做到这一点。最后一部分告诉您有关 301 重定向的信息,您应该使用它来指示搜索引擎爬虫可以在您希望的 URL 下找到该页面。

不要忘记查看 url-encoding,应该可以为您节省一些工作并提供更高质量的 url。

以下是博客文章中的一些重要片段:

设置路由:

routes.MapRoute( 
    "ViewProduct", 
    "products/{id}/{productName}", 
    new { controller = "Product", action = "Detail", id = "", productName = "" } 
);

将名称部分添加到您的 Controller 并检查它是否是正确的名称:
public ActionResult Detail(int id, string productName) 
{ 
    Product product = IProductRepository.Fetch(id); 

    string realTitle = product.Title; // Add encoding here

    if (realTitle != urlTitle) 
    { 
        Response.Status = "301 Moved Permanently"; 
        Response.StatusCode = 301; 
        Response.AddHeader("Location", "/Products/" + product.Id + "/" + realTitle); // Or use the UrlHelper here
        Response.End(); 
    }

    return View(product); 
}

更新
网址显然已损坏。本文描述的功能大致相同:http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx

感谢 Stu1986C 的评论/新链接!

关于asp.net-mvc - 从 Controller 更改 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13489801/

相关文章:

c# - Asp.Net MVC 有很多常量来处理 Controller /操作重定向

html - ASP.NET MVC View HTML 折叠展开

javascript - 如果我在 mvc 中通过 jquery 填充字段,则显示必需的验证错误

javascript - AngularJS ui-router 带有可选查询参数的状态

javascript - Backbone.js:查看状态和路由

asp.net - 当不匹配路由时,OWIN 中的 WebApi 总是返回 200 而不是 404

javascript - Angular ui 路由器可选的 url 参数

.net - LINQ 到 SQL : How to check if any item in one entity collection exists in another entity collection?

url - 戈兰 : Passing a URL as a GET parameter

c# - 安全地将变量值从一个页面传递到另一个页面