我正在尝试验证服务收到的HTTP请求。我想检查是否存在所有必需的标头等。如果没有,我想抛出一个异常,在某些地方,它会设置一个正确的响应代码和响应的状态行。我不想将用户重定向到任何特定的错误页面,只需发送答案。
我想知道我应该把代码放在哪里?我的第一个猜测是在Application_BeginRequest
中验证请求,在错误上抛出异常并在Application_Error
处理它。
例如:
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;
}
}
显然,在这种情况下,Visual Studio会在Application_BeginRequest
中抱怨未处理的异常。它可以工作,因为给定的代码返回给客户端,但我觉得这种方法有问题。
[编辑]: 我已经删除了关于自定义状态行的第二个问题,因为这些问题并没有真正联系起来。
感谢您的帮助。
答案 0 :(得分:8)
当抛出异常时,Visual Studio会默认中断执行。您可以通过转到Debug - >来更改此行为。异常并取消选中公共语言运行库异常旁边的复选框。但是,这里的主要问题是你抛出异常只是为了捕获它并在响应上设置状态代码。你可以做到这一点,而不会抛出异常。 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();
}
}