为什么ASP.NET MVC URL需要索引

时间:2016-04-29 19:12:04

标签: c# asp.net-mvc asp.net-mvc-routing

努力解决如何实现以下目标

http://localhost/star/regulus

唯一可行的方法是拥有

的网址
http://localhost/star/index/regulus

这是我的路线

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute( "", "star/{sstar}", new { Controller = "star", id = UrlParameter.Optional });

在Controller中,我将View设置为: -

return View("~/views/star.cshtml", oStar);

所以你可以看到我没有使用Index.cshtml

任何想法如何获得顶级网址,而不是第二个。

1 个答案:

答案 0 :(得分:2)

您需要重新安排路线

routes.MapRoute(
    name: "StarRoute",
    url: "star/{sstar}",
    defaults: new { controller = "Star", action = "Star", sstar = UrlParameter.Optional}
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
  

默认控制器通常应该是最后注册的路径

假设控制器

public class StarController :Controller {
    public ActionResult Star(string sstar){
        //...other code that uses sstar parameter
        return View();
    }
}

视图应位于...

~/Views/Star/Star.cshtml 

...以便使用以下URI:

http://localhost/star/regulus  
http://localhost/star?sstar=regulus
http://localhost/star/sirius  
http://localhost/star?sstar=sirius