In C# MVC can you set a global behavior which each action method must carry out before processing the rest of the request?

StackOverflow https://stackoverflow.com/questions/18975438

質問

I've got a rather large MVC web application and I am repeating an action in each controller to see if a customer has completed the application process (in which case a flag is set on their profile which I check against). Ideally I want to remove this code from each action method and have it applied to all action methods which return an action result.

役に立ちましたか?

解決

You could make a custom attribute that handles this for you, you could have the attribute at the Controller level or ActionResult level.

[CompletedApplication("User")]
public ActionResult YourAction
{
    return View();
}

public class CompletedApplicationAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Your logic here
        return true;
    }
}

他のヒント

If all expected controller inherited from some BaseController than using that, common behavior can be set.

public class HomeController : BaseController
{
}

and BaseContoller will be like

public class BaseController : Controller
{
     protected BaseController(common DI)
     {
     }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      // some logic after action method get executed      
        base.OnActionExecuted(filterContext);
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       // some login before any action method get executed

       string actionName = filterContext.RouteData.Values["action"].ToString(); // Index.en-US

        filterContext.Controller.ViewBag.SomeFlage= true;
    }

  // If Project is in MVC 4 - AsyncContoller support, 
  //below method is called before any action method get called, Action Invoker

   protected override IActionInvoker CreateActionInvoker()
    {       
        return base.CreateActionInvoker();
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top