Pregunta

In my AdministratorController I have an action with custom attribute:

[AuthorizedOnly (Roles = "admin, superadmin")]
public ActionResult Index()
{...}

The attribute is:

class AuthorizedOnlyAttribute : AuthorizeAttribute
{
    public AuthorizedOnlyAttribute()
    {
        View = "~/Views/Main/Index.cshtml";
        Master = String.Empty;
    }
    public String View { get; set; }
    public String Master { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        CheckIfUserIsAuthenticated(filterContext);
    }
    private void CheckIfUserIsAuthenticated(AuthorizationContext filterContext)
    {
        if(filterContext.Result == null)
            return;
        if(filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            if(String.IsNullOrEmpty(View))
                return;
            var result = new ViewResult{ViewName = View, MasterName = Master};

            filterContext.Result = result;
        }
    }

It correctly shows me the view that I need: ~/Views/Main/Index.cshtml But in my browser URL is still from Administrator controller: .../Administrator/Index How can I redirect to the View that I need, so that URL would also change?

Thanks a lot in advance!

¿Fue útil?

Solución

Try this

string retUrl = filterContext.HttpContext.Request.RawUrl;
filterContext.Result =
                 new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary 
                         {{ "controller", "Main" },
                          { "action", "Home" },
                          { "returnUrl",    retUrl } });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top