gpt4 book ai didi

c# - 在类中访问模拟的 Request.ServerVariables

转载 作者:行者123 更新时间:2023-11-30 22:33:16 25 4
gpt4 key购买 nike

我模拟了 Controller 中使用的服务器变量。

request.SetupGet(x => x.ServerVariables)
.Returns(new System.Collections.Specialized.NameValueCollection
{
{"SERVER_NAME","localhost"},
{"SCRIPT_NAME","localhost"},
{"SERVER_PORT","80"},
{"HTTPS","www.melaos.com"},
{"REMOTE_ADDR","127.0.0.1"},
{"REMOTE_HOST","127.0.0.1"}
});

我可以在 Controller 中获取服务器变量的值,但不能在模型类中获取。为什么会这样?

在 Controller 和 Model 中获取值的唯一区别是,在 Controller 中我们编写 HttpContext.Request.ServerVariables 而在 Model 中我们编写 HttpContext.Current.Request.ServerVariables.

它们有什么不同吗?我怎样才能在模型中获得这些值。

最佳答案

while in Model we write HttpContext.Current.Request.ServerVariables.

HttpContext.Current 是问题所在。它是一个静态属性,您不能模拟,也不能在 ASP.NET 上下文(例如单元测试)之外使用。因此,如果您使用 HttpContext.Current,则无法对您的应用程序进行单元测试。这就是说你不应该在你的模型中使用任何 HTTP 特定的工件。您应该直接将 Controller 中的值传递给模型,这样模型就不会尝试获取它们。

关于c# - 在类中访问模拟的 Request.ServerVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8383554/

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