gpt4 book ai didi

c# - 始终创建一个新的 HttpContextWrapper 是否安全?

转载 作者:行者123 更新时间:2023-11-30 12:36:05 27 4
gpt4 key购买 nike

我试图通过使用一些 ASP.NET MVC 对象,特别是 HttpContextWrapper,使现有的 ASP.NET Web 表单应用程序更易于单元测试。我看过它的用法示例,它们总是创建一个新对象。我用 Reflector 反汇编源代码,看到它所做的只是存储传递的 HttpContext。但是我很好奇始终创建 HttpContextWrapper 的新实例或以某种方式遵循单例模式是否安全?下面是我在我的应用程序中使用的类

public static class AppHttpContext {
public static HttpContextBase Current { get { return Getter(); } }

public static void SetContext(Func<HttpContextBase> getter) {
Getter = getter;
}

private static Func<HttpContextBase> Getter = () => new HttpContextWrapper(HttpContext.Current);
}

我使用它类似于 HttpContext.Current

AppHttpContext.Current.Session["blah"] = "something";

最佳答案

您的 AppHttpContext 类非常棒。它完美地抽象了 HttpContext 并允许进行单元测试。使用 HttpContextWrapper 是安全的。作为一项改进,您可以使此类成为非静态类,而不是使用静态 SetContext 方法,您可以将委托(delegate)注入(inject)构造函数。然后所有需要使用上下文的类(通常那些应该只限于您的网络表单页面)可以采用 AppHttpContext 的实例。

关于c# - 始终创建一个新的 HttpContextWrapper 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3990879/

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