简体   繁体   中英

MVC4 redirect to ChildActionOly method from c# method

i have a custom authorize attribute class where i need to redirect to a Action which is decorated with ChildActionOnly attribute when user not authorized,

public override void OnAuthorization(AuthorizationContext filterContext)
{
    HttpContextBase context = filterContext.RequestContext.HttpContext;
    if (context.User.Identity.IsAuthenticated)
    {
        var user = AppData.CurrentUser;
        if (string.IsNullOrEmpty(user.GroupName))
        {
            filterContext.Result = new RedirectResult("~/Error/Unauthenticated");
        }
    }
}

and the error controller is

[AllowAnonymous]
[ChildActionOnly]
public class ErrorController : Controller
{
    public ActionResult Unauthorized() { return View(); }
    public ActionResult Unauthenticated() { return View(); }
}

i'm getting application error

The action 'Unauthorized' is accessible only by a child request.

Why is it so dangerous that a user potentially could navigate to the Unauthorized action if you remove the [ChildActionOnly] attribute? In worst case they don't get the information what page they are not supposed to see since they are not redirected from that controller/action that redirects them to this Unauthorized view. In normal case when a user is not authorized they are sent to a login page with the referrer as a url-parameter so they can be sent back once they authorize themselves, maybe not an option here?

With that said, you could with code send TempData when an error occours. TempData is a key/value-pair object that persists within an redirect so send some special value that you check for (See MSDN ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM