简体   繁体   English

调用HttpContext.Request时如何避免HttpException?

[英]How to avoid a HttpException when calling HttpContext.Request?

So HttpContext.Request throws if called within a global start 因此,如果在全局启动内调用,则抛出HttpContext.Request

public HttpRequest get_Request()
{
    if (this.HideRequestResponse)
    {
        throw new HttpException(SR.GetString("Request_not_available"));
    }
    return this._request;
}

This is actually documented 这实际上已记录在案

ASP.NET will throw an exception if you try to use this property when the HttpRequest object is not available. 如果在HttpRequest对象不可用时尝试使用此属性,ASP.NET将引发异常。 For example, this would be true in the Application_Start method of the Global.asax file, or in a method that is called from the Application_Start method. 例如,在Global.asax文件的Application_Start方法中或在从Application_Start方法调用的方法中都是如此。 At that time no HTTP request has been created yet. 那时还没有创建HTTP请求。

Is there a way of checking if a HttpContext.Request is in a state that it can be retrieved without throwing the exception? 有没有办法检查HttpContext.Request是否处于可以检索而不抛出异常的状态? Effectively I want to write a TryGetRequest helper method. 实际上我想写一个TryGetRequest帮助方法。

  • Reflection is not an option. 反思不是一种选择。 It needs to be a public API. 它需要是一个公共API。
  • I dont have access to the application context. 我无法访问应用程序上下文。 this is generic logging code. 这是通用的日志记录代码。 So setting some flag when startup has finished is not an option 因此,在启动完成时设置一些标志不是一种选择

As deostroll observed, it is reasonable and may in fact be necessary to rely on the ASP.NET application lifecycle to determine when the current HttpRequest has become available. 在观察到deostroll时 ,这是合理的,实际上可能需要依赖ASP.NET应用程序生命周期来确定当前HttpRequest何时可用。 The generic logging code is presumably dependent at the very least on HttpContext.Current or some other reference to the current HttpContext instance. 通用日志记录代码可能至少依赖于HttpContext.Current或对当前HttpContext实例的一些其他引用。 If that assumption holds true, then an HttpModule can be implemented that stores a flag in the HttpContext.Items collection when the BeginRequest event fires. 如果该假设成立,那么可以实现一个HttpModule ,它在BeginRequest事件触发时在HttpContext.Items集合中存储一个标志。 The static TryGetRequest helper method can test for the presence of that flag to determine whether it is safe to use HttpContext.Request . 静态TryGetRequest帮助器方法可以测试该标志的存在,以确定使用HttpContext.Request是否安全。

Perhaps like this: 也许是这样的:

public class HttpRequestHelper : IHttpModule
{
    private const string HttpRequestIsAvailable = "HttpRequestIsAvailable";

    public static bool TryGetRequest(HttpContext context, out HttpRequest request)
    {
        request = null;
        if (context != null)
        {
            if (context.Items.Contains(HttpRequestIsAvailable))
                request = context.Request;
        }
        return (request != null);
    }

    #region IHttpModule

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
    }

    private void context_BeginRequest(object sender, EventArgs e)
    {
        ((HttpApplication)sender).Context.Items.Add(HttpRequestIsAvailable, true);
    }

    #endregion
}

The module must be registered in web.config (assuming IIS 7.0 integrated pipeline): 该模块必须在web.config中注册(假设IIS 7.0集成管道):

  <system.webServer>
    <modules>
      <add name="HttpRequestHelper" type="Utility.HttpRequestHelper" />
    </modules>
  </system.webServer>

The logging code would use the helper method like this: 日志代码将使用这样的帮助方法:

HttpRequest request;
if (HttpRequestHelper.TryGetRequest(HttpContext.Current, out request))
    LogWithRequest(request, message);
else
    LogWithoutRequest(message);

The implementation does not rely on private API's or reflection. 实现不依赖于私有API或反射。 It relies on a flag, but the state information remains with the HttpContext instance and is well encapsulated. 它依赖于一个标志,但状态信息保留在HttpContext实例中,并且封装良好。

为什么不用try,catch块将调用包装到HttpContext.Request ,然后你可以捕获异常并相应地修改你的行为。

没有使用反射是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 HttpContext.Request 作为对象读取? - Reading HttpContext.Request as object? 从HttpContext.request对象获取列表 - Get a list from an HttpContext.request object HttpContext.Request从listBox的项目? - HttpContext.Request the items from listBox? HttpContext.Request [“ x”]引发异常 - HttpContext.Request[“x”] throws exception 使用最小起订量填充httpcontext.request - using moq to populate httpcontext.request HttpContext.Request或HttpContext.Current.Request URL中是否缺少“#”字母? - '#' letter is missing in HttpContext.Request or HttpContext.Current.Request url? 如何将 HttpContext.Request/Response 的标头与 HttpRequestMessage.Request/Response 的标头进行比较? - How do I compare headers from HttpContext.Request/Response with those of HttpRequestMessage.Request/Response? HttpContext.Request 和 Request a .NET Core controller 有什么区别? - What is the Difference between HttpContext.Request and Request a .NET Core controller? 传递HttpContext.Request参数或使用静态实例? - Pass HttpContext.Request parameter around or use static instance? HttpContext.HideRequestResponse的内部解决方法是什么? 检测HttpContext.Request是否真的可用? - Workaround for HttpContext.HideRequestResponse being internal? Detect if HttpContext.Request is really available?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM