I am trying to check the HTTP request received by the service. I want to check if all required headers are present, etc. If not, I would like to make an exception that in some place would set the correct response code and response status bar. I donβt want to redirect the user to any specific error page, just send a response.
I wonder where should I put the code? My first assumption was to check the requests in Application_BeginRequest , throw an exception from the error, and handle it in Application_Error .
For instance:
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 because this code is being returned to the client, but I feel that something is wrong with this approach.
[Edit]: I deleted the second question about the custom status bar, as these questions are not related.
Thanks for the help.
source share