我模拟了 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/