RedirectToAction重定向错误的其他命名空间asp.net mvc

时间:2017-01-25 08:50:20

标签: c# asp.net-mvc routetable

我写了这样的路线。

routes.MapRoute(
    name: "AdminECommerce",
    url: "Admin/ECommerce/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "AdminEcommerce.Controllers" }
);

routes.MapRoute(
    name: "ECommerce",
    url: "ECommerce/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "Ecommerce.Controllers" }
);

routes.MapRoute(
    name: "User",
    url: "Plugin/User/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "User.Controllers" }
);

routes.MapRoute(
    name: "UserRegistration",
    url: "Plugin/UserRegistration/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "UserRegistration.Controllers" }
);

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

当我想在一个Action中使用RedirectToAction到同一个Controller中的其他Action时,它会重定向到其他地方。

例如,我希望它将我重定向到

Plugin/UserRegistration/Register/Register

但是,它发送给我

Admin/ECommerce/Register/Register

我必须提到我的控制器在其他库中。

我的代码出了什么问题?

更新:控制器Registration

public ActionResult Register()
    {
        ViewBag.securityQuestions = _dataRepository.GetContext().User_SecurityQuestion;
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RegisterNewUser(User_User model, FormCollection collection)
    {

        try
        {
            // register new user 
              ...
            return RedirectToAction("Register");
        }
        catch
        {
            // making error messages 
              ...
            return RedirectToAction("Register");
        }

我也尝试了这个,

return RedirectToAction("Register","Registration");

它不起作用。

1 个答案:

答案 0 :(得分:2)

ASP.NET MVC识别这两个路由,与UriTemplate相同

routes.MapRoute(
    name: "AdminECommerce",
    url: "Admin/ECommerce/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "AdminEcommerce.Controllers" }
);

routes.MapRoute(
    name: "UserRegistration",
    url: "Plugin/UserRegistration/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    namespaces: new []{ "UserRegistration.Controllers" }
);

MVC从上到下读取Route表,以便将请求的Url与UriTemplate匹配。因此,在这种情况下,它将选择第一个模板。

尝试改为使用RedirectToRoute

return RedirectToRoute("Registration", new 
{ 
    controller = "Registration", 
    action = "Register"
});