user266909 user266909 - 2 months ago 6
ASP.NET (C#) Question

How to find if a filter is in the C# GlobalFilter

The ASP.Net MVC has the GlobalFilters.Filters. I want to find if RequireHttpsAttribute is in the GlobalFilters. I tried using GlobalFilters.Filters.Contains() but not knowing what type the RequiredHttpsAtrribute is. Thanks.

Answer

You can use some LINQ:

var hasAttribute = GlobalFilters.Filters
    .Where(f => f.Instance is RequireHttpsAttribute)
    .Any();

Filters collection has a list of System.Web.Mvc.Filter elements. I filtered global filters collection for a filter, whose property Instance is of type RequireHttpsAttribute. Then I used Any to find out if there is at least one element in the collection.

The result hasAttribute is true if global filters collection has RequireHttpsAttribute, and false if not.

Comments