【问题标题】:Redirect to action based on role not working. Maybe routing needed?根据角色不工作重定向到操作。也许需要路由?
【发布时间】:2015-08-12 21:02:13
【问题描述】:

我有以下控制器

public class GlobalAdminController : Controller
{
    // GET: GlobalAdmin
    [AuthorizeUser(Roles = "admin")]
    public ActionResult Index()
    {
        return View();
    }
}

还有家庭控制器,它是应用程序的主要登录页面

public ActionResult Index()
{
    if(User.IsInRole("admin"))
    {
        RedirectToAction("Index", "GlobalAdmin");
    }
    return View();
}

重定向到操作在调试器中执行 但是索引操作本身并未在全局管理员上执行

我想知道是否有更好的方法来做到这一点?也许通过路由?

【问题讨论】:

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


    【解决方案1】:

    您必须使用return 向浏览器提供重定向信息(url)。并且浏览器将重定向到新位置。

    public ActionResult Index()
    {
        if(User.IsInRole("admin"))
        {
           return RedirectToAction("Index", "GlobalAdmin");
        }
        return View();
    }
    

    路由的重点是提供一种从控制器访问操作的方法。而不是访问GlobalAdmin/Index,而是使用路由提供另一种方式,例如admin/index

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

    【讨论】:

    • 是否也可以使用 RouteConfig.cs?例如,默认值可以根据角色而有所不同吗? routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
    • @EstebanV 我认为这对某些事情没有帮助。来自同一控制器的操作不会因角色而异。如果是这样,也许你想拆分控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2020-01-03
    相关资源
    最近更新 更多