具有不同控制器的相同路由参数'动作方法在Asp .Net MVC中导致错误

时间:2015-07-29 11:41:47

标签: asp.net-mvc controller action attributerouting

我正在使用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路线。我知道这是因为相同的路线模式,但我不能把它改成另一件事。 我该如何处理这种情况? 感谢

1 个答案:

答案 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();
}