pretty URL ASP.NET MVC [英] Pretty URL ASP.NET MVC
问题描述
我怎样才能获得pretty网址,像本地主机:8888 /新闻/例,后以代替localhost:8888 /主页/细节/ 2
我的HomeController有详细信息的方法如下
公共ActionResult的详细信息(INT ID)
{
VAR ArticleToView =(从_db.ArticleSet m其中m.storyId == ID选择M)。首先(); 返回查看(ArticleToView);
由于ASP.NET路由系统有些复杂,有很多种方法来完成你的描述。
首先,你只是想有详细信息方法pretty网址是什么?如果是这样,你可能会考虑重新命名的HomeController到NewsController或移动详细方法到一个新的NewsController类 - 即会自动形成的URL /新闻
部分。如果你不想 /详细信息
部分,则可以重命名您的详细方法首页
,因为这将是自动通过 /新闻
调用。最后,你需要改变你的内部编号
参数为字符串名称
。
如果您想许多自定义的网址,你将不得不定义自己的路线以下是这样做的两种方式:
1。
我发现最简单的方法是将使用基于属性的 ASP.NET MVC路由映射 。这样一来,所有你需要做的就是你想要的pretty URL每个方法添加一个属性,并指定你想要的网址。
首先,你必须遵循一些步骤来设置基于属性的路由映射系统,该链接所概述。
完成这些步骤后,你必须改变你的方法是这样的:
[URL(新闻/ {名})]
公众的ActionResult详细信息(字符串名称)
{
VAR ArticleToView =(从_db.ArticleSet m其中m.storyId == ID选择M)。首先(); 返回查看(ArticleToView);
}
2。
或者,你可以的手动的Global.asax.cs
定义自定义路线即可。在你的的RegisterRoutes
方法,您可以添加在中间以下内容:
routes.MapRoute(
NewsDetails
新闻/ {name}的
新{控制器=新闻,行动=详细信息,名字=}
);
How can I get pretty urls like localhost:8888/News/Example-post instead of localhost:8888/Home/Details/2
My HomeController has the following for the Details method
public ActionResult Details(int id)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyId == id select m).First();
return View(ArticleToView);
As the ASP.NET routing system is somewhat complicated, there are many ways to accomplish what you describe.
First of all, do you just want to have a pretty URL for the Details method? If so, you might consider renaming HomeController to NewsController or moving the Details method into a new NewsController class - that will automatically form the /News
part of the URL. If you don't want a /Details
part, you might rename your Details method Index
, as that will be automatically called by /News
. Finally, you need to change your int id
parameter into string name
.
If you want many custom URLs, you're going to have to define your own routes. Here are two ways of doing this:
1. The easiest way I've found is to use an ASP.NET MVC Attribute-Based Route Mapper. That way, all you have to do is add an attribute on each method you want a pretty URL for and specify what URL you want.
First, you must follow a few steps to set up the attribute-based route mapping system, as outlined on that link. After completing those steps, you must change your method to look like this:
[Url("News/{name}")]
public ActionResult Details(string name)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyId == id select m).First();
return View(ArticleToView);
}
2.
Alternatively, you can define your custom routes manually in Global.asax.cs
. In your RegisterRoutes
method, you can add the following in the middle:
routes.MapRoute(
"NewsDetails",
"News/{name}",
new { controller = "News", action = "Details", name = "" }
);
这篇关于pretty URL ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!