这是我第一次在ASP.Net Mvc上处理路由,我试图做一些像StackOverflow一样的问题。使用简单的自定义路由
我有我叫News
控制器,它富人他的行动像News/
,News/Create
,News/Edit/1
等我想补充的,而不是电网这个自定义路由News/1
,将返回的消息本身的可视化,默认指数News/
节目。
这是我的路线:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ViewNews",
url: "{controller}/News/{newsId}",
defaults: new { controller = "News", action = "Index" },
constraints: new { newsId = @"\d+" }
);
首当其冲是默认路由,第二个是我试过了,下面this post。但它只是给我这个错误(在此网址News/1
):
'/'应用程序中的服务器错误。
无法找到该资源。
我想知道我做错了什么,一旦它甚至没有达到行动。如果我尝试News/
它很好。
我与我的行动做到了这一点:
public ActionResult Index(int? id)
{
if (id != null)
{
var news = _newsService.GetView((int)id);
if (news != null)
{
return View("News", news);
}
else
{
return RedirectToAction("Index", "Home");
}
}
return View();
}
这将是很好,如果有人能告诉怎么做,像这样:News/1/news-title-here
。
好了,我没想到这将有所作为。我会尽力。 – DontVoteMeDown
是的,我意识到我应该将action参数更改为'newsId'。它工作的兄弟,谢谢。 – DontVoteMeDown
@DontVoteMeDown没问题,很高兴能帮到你。 – Silvermind