gpt4 book ai didi

c# - HttpContext.HideRequestResponse 的解决方法是内部的?检测 HttpContext.Request 是否真的可用?

转载 作者:IT王子 更新时间:2023-10-29 04:14:56 26 4
gpt4 key购买 nike

我们正在迁移应用程序以使用 IIS7 集成模式。在设计为在 HTTP 请求上下文或不在上下文中工作的库代码中,我们通常有这样的代码:

if (HttpContext.Current != null &&
HttpContext.Current.Request != null) {

// do something with HttpContext.Current.Request

} else {

// do equivalent thing without HttpContext..

}

但在 IIS7 集成模式下,每当从 Application_Start 调用此代码时,对 HttpContext.Current.Request 的检查都会引发异常。

protected void Application_Start(object sender, EventArgs e)
{
SomeLibrary.DoSomethingWithHttpContextCurrentDetection();
}

结果:

System.Web.HttpException: Request is not available in this context

如何将这些调用包装在异常处理程序中并根据是否生成异常来采取措施,我如何检测请求是否真的可用。

查看 Reflector 中的 HttpContext,我发现它有一个 internal bool HideRequestResponse 字段,但它是内部的,所以我只能通过反射来访问它,这很脆弱。是否有更官方/认可的方法来确定是否可以调用 HttpContext.Request

这篇关于该主题的博文说不要使用 HttpContext,但是如何在通用库代码中确定是否可以使用 HttpContext

http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/

我正在使用那里提到的解决方法,即使用 Application_BeginRequest 和一个 initialized 字段作为 BeginRequest 的一部分只初始化一次>,但这必须在每个调用应用程序中完成,而我更愿意使库代码更健壮并处理这种情况,而不管它是从哪里调用的。

最佳答案

我会将您的代码重构为:

if (IsRequestAvailable())
{
// do something with HttpContext.Current.Request...
}
else
{
// do equivalent thing without HttpContext...
}

public Boolean IsRequestAvailable()
{
if (HttpContext.Current == null)
return false;

try
{
if (HttpContext.Current.Request == null)
return false;
}
catch (System.Web.HttpException ex)
{
#if DEBUG
// Testing exception to a magic string not the best practice but
// it works for this demo.
if (ex.Message == "Request is not available in this context")
return false;

throw;
#else
return false;
#endif
}

return true;
}

你的问题要求不要使用异常处理(我假设是出于性能原因),我的回答是。但是,通过将代码从使用“If (HttpContext.Current != null && HttpContext.Current.Request != null)”更改为“If (IsRequestAvailable())”,当您找到回答如何不使用异常处理。

关于c# - HttpContext.HideRequestResponse 的解决方法是内部的?检测 HttpContext.Request 是否真的可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2609512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com