我正在使用Asp .Net Mvc的属性路由功能。 我的第一个动作如下所示放在SurveyController
中 [Route("{surveyName}")]
public ActionResult SurveyIndex()
{
return View();
}
我的第二个动作如下所示放在MainCategoryController
中 [Route("{categoryUrlKey}")]
public ActionResult Index(string categoryUrlKey)
{
return View();
}
我没有使用基于约定的路由。 下面是我的RouteConfig。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
routes.MapAttributeRoutes();
}
现在问题是,当我点击一个调查时,它会重定向到MainCategory / Index路线。我知道这是因为相同的路线模式,但我不能把它改成另一件事。 我该如何处理这种情况? 感谢
答案 0 :(得分:1)
您应该在MainCaregoryController
上为路由添加前缀,或者在控制器级别为:
[RoutePrefix("category")]
public class MainCategoryController : Controller {
行动级别的或,如下所示:
[Route("category/{categoryUrlKey}")]
public ActionResult Index(string categoryUrlKey)
{
return View();
}
路线不应该发生冲突。这条路线:
[Route("{categoryUrlKey}")]
public ActionResult Index(string categoryUrlKey)
{
return View();
}
匹配任何字符串,并将该字符串值传递给操作,因此如果没有前缀,它将匹配:
http://localhost/validcategorykey
和
http://localhost/something/id/isthispointmakingsense
,您的categoryUrlKey
参数在第一个实例中等于"validcategorykey"
,在第二个实例中等于"something/id/isthispointmakingsense"
。
现在这条路线:
[Route("{surveyName}")]
public ActionResult SurveyIndex()
{
return View();
}
这只是赢得了工作期。这需要更改为:
[Route("survey/{surveyName}")]
public ActionResult SurveyIndex(string surveyName)
{
return View();
}