Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a proper way to validate HTTP requests and return specific HTTP responses in Global.asax?

I'm trying to validate an HTTP request received by a service. I want to check if all required headers are present etc. If not, I'd like to throw an exception, that would, in some place, set a proper response code and status line of the response. I don't want to redirect user to any specific error page, just send the answer.

I wonder where should I put the code? My first guess was to validate requests in Application_BeginRequest, throw an exception on error and handle it in Application_Error.

For example:

 public void Application_BeginRequest(object sender, EventArgs e)
 {
     if(!getValidator.Validate(HttpContext.Current.Request))
     {
         throw new HttpException(486, "Something dark is coming");
     }
 }

 public void Application_Error(object sender, EventArgs e)
 {
     HttpException ex = Server.GetLastError() as HttpException;
     if (ex != null)
     {
            Context.Response.StatusCode = ex.ErrorCode;
            Context.Response.Status = ex.Message;
     }
 }

Apparently, in such cases Visual Studio complains about an unhandled exception in Application_BeginRequest. It works, as the given code is returned to the client, but I feel that something is wrong with this approach.

[Edit]: I've removed the second question about custom status line, as these questions are not really connected.

Thanks for help.

like image 719
Piotr Zierhoffer Avatar asked Aug 23 '11 10:08

Piotr Zierhoffer


1 Answers

Visual studio breaks execution by default when an exception is thrown. You can change this behavior by going to Debug -> Exceptions and uncheck the check boxes next to common language runtime exceptions. However, the main problem here is you are throwing an exception just so you can catch it and set the status code on the response. You can do that without throwing an exception. e.g.

void Application_BeginRequest(object sender, EventArgs e)
{
    if(!getValidator.Validate(HttpContext.Current.Request))
    {
        HttpContext.Current.Response.StatusCode = 403 
        var httpApplication = sender as HttpApplication;
        httpApplication.CompleteRequest();
    }
}
like image 169
Kiran Mothe Avatar answered Oct 20 '22 21:10

Kiran Mothe