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.