0

Is there a way to add a filter/IsLocal() check to a specific controller?

I know from this answer (https://stackoverflow.com/a/30573590/1887101) I can apply a filter globally, but is there a simple way to only apply a filter to a single controller within an application of many controllers?

Bryan Williams
  • 135
  • 1
  • 11
Adjit
  • 9,403
  • 8
  • 45
  • 86

1 Answers1

0

What confused me about all of this is that there are actually two different AuthorizeAttributes:

  • System.Web.Http.AuthorizeAttribute
  • System.Web.Mvc.AuthorizeAttribute (use this one for Controllers)

First, create your LocalRequestOnly authorize attribute.

using System.Web;
using System.Web.Mvc;

namespace myWebsite
{
    public class LocalRequestOnlyAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return httpContext.Request.IsLocal;
        }
    }
}

Then add [LocalRequestOnly] attribute to either a Controller or Action (it'll work on both).

[LocalRequestOnly]
public class HomeController : Controller
{...}
Bryan Williams
  • 135
  • 1
  • 11
  • 1
    Thanks, I ended up doing something similar, but I am using `AspNetCore` and `HttpRequest` doesn't have `IsLocal` available, so I implemented my own IsLocal extension method – Adjit Jun 04 '20 at 17:44
  • The filters and attributes seem to me to be more complicated than they need to be. And like everything else in .NET Core, they just got more complex (although more powerful as well). I like a lot of what they've done in .NET Core, but what I don't like is that they threw out so much of the .NET Framework MVC architecture unnecessarily and replaced it with something new, seemingly just because they could. So now there's this unnecessary learning curve when switching to Core. – Bryan Williams Jun 04 '20 at 17:50