0

I am using MVC3, ASP.NET4.5, C# and Razor.

I would like to set an attribute globably ie AuthorizeAttribute. However I need to ensure that some classes and/or actions ignore this global setting. Is it possible to decorate a class and/or action to ensure this, and if so how?

Many thanks.

SamJolly
  • 6,347
  • 13
  • 59
  • 125

1 Answers1

1

You can use the [AllowAnonymous] attribute (which is the default in ASP.NET MVC) to override your [Authorize] attribute

Assuming you have added your customized authorization logic to the default FilterConfig class:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new MyCustomAuthorizationAttribute());
    }
}

You can override that setting by decorating your controllers/action methods with [AllowAnonymous]:

// To allow anonymous access to all action methods
[AllowAnonymous]
public class MyController : Controller
{
    // Only allow the Index action method to be called anonymously
    [AllowAnonymous]
    public ActionResult Index()
    {
    }
}
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
  • Thank you for this. I meant this question to be about how to exclude attribute filters from controllers and actions. I was just using Authorize as an example. I have come across Filter Providers. Just reading up on it now. For Example I have anoter attribute here called "IsValidURLRequestAttribute" ie [IsValidURLRequest] which I want to apply globally and have something like [IsValidURLRequest(false)] on all classes or actions where it should not be used. – SamJolly Jun 06 '14 at 02:01
  • 2
    @SamJolly In that case, the cleanest way is to derive your controllers from an abstract controller and override the the `On` Methods. You can read more on [Filtering in ASP.NET MVC](http://msdn.microsoft.com/en-us/library/gg416513(vs.98).aspx) – rexcfnghk Jun 06 '14 at 02:06