Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Action Filter's data in Controller Action

Tags:

asp.net-mvc

[ApiBasicAuthorize]
public ActionResult SignIn()
{

}

I have this custom filter called ApiBasicAuthorize. Is it possible to access ApiBasicAuthorize's data (properties etc) inside the controller action SignIn?

If not, how do I pass data from the filter to controller action?

like image 635
Gautam Jain Avatar asked Aug 12 '11 11:08

Gautam Jain


People also ask

What is action method in controller?

An action (or action method ) is a method on a controller that handles incoming requests. Controllers provide a logical means of grouping similar actions together, allowing common sets of rules (e.g. routing, caching, authorization) to be applied collectively. Incoming requests are mapped to actions through routing.

Which method is used to pass data from controller to view?

ViewData, ViewBag, and TempData are used to pass data between controller, action, and views. To pass data from the controller to view, either ViewData or ViewBag can be used. To pass data from one controller to another controller, TempData can be used.

What is the use of action filters in an MVC application?

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.


2 Answers

There is a dictionary called items attached to the HttpContext object. Use this dictionary to store items shared across components during a request.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    filterContext.HttpContext.Items["key"] = "Save it for later";

    base.OnAuthorization(filterContext);
}

Then anywhere in your code later in the request...

var value = HttpContext.Current.Items["key"];
like image 158
Jeremy Bell Avatar answered Nov 21 '22 14:11

Jeremy Bell


    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var rd = filterContext.RouteData;

        //add data to route
        rd.Values["key"]="Hello";

        base.OnAuthorization(filterContext);
    }



public ActionResult(string key)
{
 //key= Hello
return View();
}
like image 36
Praveen Prasad Avatar answered Nov 21 '22 14:11

Praveen Prasad