【问题标题】:Business Class unable to reference HTTPContext业务类无法引用 HTTPContext
【发布时间】:2011-06-11 10:50:39
【问题描述】:

我在我的解决方案中将业务层设置为另一个 C# 项目,我需要调用 HttpContext 但无论我尝试什么,我都无法正确引用它。

我尝试让 Visual Studio 获取所需的引用,但没有成功,我还尝试手动放置对 System.Web 的引用,但这些似乎不起作用。

我还注意到 Session 也没有被发现。

下面是我用过的代码sn-p

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace BussinessLayer
{
    class UserPermissions
    {
        public void redirectToLogin()
        {

            if (Session["user"] == null)
            {
                HttpContext.
                if (HttpContext.Current.Request.Cookies["userName"] == null)
                {
                    HttpContext.Current.Response.Redirect("/login.aspx");
                }

            }
        }
    }
}

有人知道为什么找不到 HttpContext 或 Session 吗?

【问题讨论】:

  • 当您说“参考”时 - 您的意思是您遇到了编译器错误吗?还是 HttpContext.Current 以 null 的形式返回?

标签: c#


【解决方案1】:

这与定位 .NET 4 客户端配置文件有关。您可以通过将项目重新定位到完整的 .NET Framework 4 来解决此问题。

【讨论】:

    【解决方案2】:

    HttpContext.Current 不适合业务层,可以使用HttpContextBase 代替

        public static class HttpContextHelper {
        private static object lockObj = new object();
        private static HttpContextBase mockHttpContext;
    
        /// <summary>
        /// Access the HttpContext using the Abstractions.
        /// </summary>
        public static HttpContextBase Current {
            get {
                lock (lockObj) {
                    if (mockHttpContext == null && HttpContext.Current != null) {
                        return new HttpContextWrapper(HttpContext.Current);
                    }
                }
    
                return mockHttpContext;
            }
    
            set {
                lock (lockObj) {
                    mockHttpContext = value;
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要引用可以在 GAC 中找到的 System.Web.dll(我的 VS2010 没有在 '.NET References' 中显示它,所以我必须手动添加它)。

      此外,如果您要分离业务层,最好让它更独立、更松散耦合。

      【讨论】:

        【解决方案4】:

        您真的,真的,真的应该不需要从您的业务层引用HttpContext。如果你这样做了,那么它就不再是一个业务层了。它是表示层的一部分,对表示引擎具有硬编码的依赖性。

        HttpContext 需要的任何值都应在表示层调用时提供给业务层对象。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-16
          • 2011-01-29
          • 1970-01-01
          • 2021-06-09
          • 2014-11-30
          • 2011-06-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多