【发布时间】:2011-08-23 10:30:00
【问题描述】:
我正在尝试验证服务收到的 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 中抱怨未处理的异常。它有效,因为给定的代码返回给客户端,但我觉得这种方法有问题。
[编辑]: 我删除了关于自定义状态行的第二个问题,因为这些问题并没有真正相关。
感谢您的帮助。
【问题讨论】:
-
WCF 在哪里发挥作用?您是否正在构建托管在 IIS 中的 REST 服务?
-
嗯,是的。我相信这是选项之一,而不是将服务托管为托管 Windows 服务/托管应用程序(根据 msdn)
标签: c# wcf global-asax