Workaround for HttpContext.HideRequestResponse being internal? Detect if HttpContext.Request is really available?

后端 未结 5 1657
逝去的感伤
逝去的感伤 2020-12-14 01:21

We\'re migrating an application to use IIS7 integrated mode. In library code that is designed to work either within the context of an HTTP request or not, we commonly have

5条回答
  •  眼角桃花
    2020-12-14 01:38

    I would refactor your code to this:

    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;
    }
    

    Your question asked not to use exception handling (I assume for performance reasons) and my answer does. However, by changing your code from using "If (HttpContext.Current != null && HttpContext.Current.Request != null)" to "If (IsRequestAvailable())" you only have one place to change the code when you find an answer how not to use exception handling.

提交回复
热议问题