Search code examples
c#asp.netsecuritybundling-and-minification

Validating Requests for BundleConfig Routes/URLs


Is there a way in ASP.NET to validate Requests' parameters sent in Virtual Paths/Routes created using the BundleConfig ScriptBundle?

Example:

I have a BundleConfig configurations as below:

bundles.Add(new ScriptBundle("~/bundles/bjqs").Include(
                "~/Scripts/bjqs-1.3.js"));

If a user sends a request like the following:

http://example.com/bundles/bjqs?v=parameter-value_to%be+validated

How do I validate the value passed in the query string v parameter against a regex before the request being handled/processed by ASP.NET?


Solution

  • You can use a custom HttpModule to intercept the request. For example:

    public class MyModule1 : IHttpModule
    {
        public void Dispose() {}
    
        public void Init(HttpApplication context)
        {
            context.AuthorizeRequest += context_AuthorizeRequest;
        }
    
        void context_AuthorizeRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
    
            // Check if the parameter is valid, your logic
            if (ValidateRequest(app.Context.Request))
            {
                // Then do nothing
                return;
            }
    
            // Otherwise, return unauthorized response
            app.Context.Response.StatusCode = 401;
            app.Context.Response.End();
        }
    }