Request Filtering for ASP.NET Core applications: Part 3 - Integrating with ASP.NET Pipeline

Oct 09, 2016     Viewed 8541 times    0 Comments
Posted in #Request Filtering 

This is the third post of a series in Request Filtering in ASP.NET Core. Last post I showed you how to build the abstractions & implementation API's to support Request Filtering in ASP.NET Core applications. In this post I illustrate how can we use and integrate the Request Filtering rules - that I mentioned them in the last post - into the ASP.NET Core pipeline.

Now let us see how we can use our implementation APIs into ASP.NET Core application such as the following:

var options = new RequestFilteringOptions()
    .AddFileExtensionRequestFilter(new FileExtensionsOptions
    {
        FileExtensionsCollection = new List
        {
            new FileExtensionsElement() { FileExtension = ".jpg", Allowed = true },
            new FileExtensionsElement() { FileExtension = ".psd", Allowed = false }
        }
    })
    .AddHttpVerbRequestFilter(new HttpVerbsOptions
    {
            AllowUnlisted = false,
            HttpVerbsCollection = new List
            {
                 new HttpVerbElement() { Verb = HttpVerb.Get, Allowed = true }
            }
    })
    .AddQueryStringRequestFilter(new QueryStringsOptions
    {
            AllowUnlisted = false,
            QueryStringsCollection = new List
            {
                 new QueryStringElement() { QueryString = "id", Allowed = true },
                 new QueryStringElement() { QueryString = "name", Allowed = false }
            }
    })
    .AddHiddenSegmentRequestFilter(new HiddenSegmentsOptions
    {
            HiddenSegmentsCollection = new List
            {
                 new HiddenSegmentElement() { Segment = "Private" }
            }
    })
    .AddHeaderRequestFilter(new HeadersOptions
    {
            HeadersCollection = new List
            {
                 new HeaderElement() { Header = "X-Auth", SizeLimit = 5 }
            }
    })
    .AddUrlRequestFilter(new UrlsOptions
    {
            DeniedUrlSequences = new[] { "me" },
            AllowedUrls = new[] { "/Home" }
    });

app.UseRequestFiltering(options);

In the code above I setup all the required request filters that my application may needs in the Configure method, simply by using an extension methods that's available on RequestFilteringOptions, after that we plug it into the pipeline like any other middleware using UseRequestFiltering which is basically use RequestFilteringMiddleware behind scene.

So whenever a request come into the application the RequestFilteringMiddleware will apply the predifine request filters to allow or deny the request that's already instantiated.

You can download the source code for this post from my RequestFiltering repository.

Twitter Facebook Google + LinkedIn


Leave a Comment