سؤال

so basically I have a custom ActionFilterAttribute and in it I override one method which looks something like this

public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
    bool shouldEnter = true;
    string redirUrl = "SomeController/SomeAction";
    // some checks here which change the value of shouldEnter;
    if (!shouldEnter)
    {
        filterContext.HttpCOntext.Response.Redirect(redirUrl);
    }
}

this is a very simple implementation of ActionFilterAttribute. Basically I check something and than decide to let the guy in or not. If I'm not letting him in than I should redirect him to some URL and I do that with the above implementation of OnActionExecuting method. but the thing is that before it goes to the someUrl the action he requested action gets executed first. Suppose I've request the page at ~/SomeController/YouShouldNotEnterHere and this action has that attribute on it. the OnActionExecuting gets invoked and than I suppose that the corresponding action of redirUrl (which is mentioned in OnActionExecuting method ) will get invoked because I redirected the Response to it, but no, first the corresponding Action of /SomeController/YouShouldNotEnterHere gets invoked (but not drawn actually in browser, but the action still consumes time) and than the corresponding action of redirUrl gets invoked (and drawn in browser). Is this some kind of bug? or this is supposed to work this way ? anyway what can I do t

هل كانت مفيدة؟

المحلول

It sounds like you are doing authorization, the proper attribute to use in this case is an AuthorizeAttribute

This will code will fix your existing attribute:

filterContext.Result = new RedirectResult { Url = redirUrl };
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top