title: What is a proper way to validate HTTP requests and return specific HTTP responses in Global.asax?
body: <p>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.</p>
  
  <p>I wonder where should I put the code? My first guess was to validate requests in <code>Application_BeginRequest</code>, throw an exception on error and handle it in <code>Application_Error</code>.</p>
  
  <p>For example:</p>
  
  <pre class="lang-cs prettyprint-override"><code> 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;
       }
   }
  </code></pre>
  
  <p>Apparently, in such cases Visual Studio complains about an unhandled exception in <code>Application_BeginRequest</code>. It works, as the given code is returned to the client, but I feel that something is wrong with this approach.</p>
  
  <p>[Edit]:
      I've removed the second question about custom status line, as these questions are not really connected.</p>
  
  <p>Thanks for help.</p>