What is the correct way to check HTTP requests and return specific HTTP responses to Global.asax?

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.

+6
source share
1 answer

Visual studio aborts the default execution when an exception is thrown. You can change this behavior by going to "Debugging" β†’ "Exceptions" and uncheck the boxes next to the runtime exceptions of the regular language. However, the main problem here is that you throw an exception so that you can catch it and set a status code for the response. You can do this 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(); } } 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(); } }

+6
source

Source: https://habr.com/ru/post/895664/


All Articles