asp.net-mvc MVC ASP.NET 中 HttpContext.Current 和 Controller.Context 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/785413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between HttpContext.Current and Controller.Context in MVC ASP.NET
提问by TonE
I am working on an MVC ASP .NET application. I am relatively new to both.
我正在开发一个 MVC ASP .NET 应用程序。我对两者都比较陌生。
In a controller I am trying to get the current log on user, for which there seem to be two ways of doing this:
在控制器中,我试图获取当前登录用户,似乎有两种方法可以做到这一点:
System.Web.HttpContext.Current.User.Identity.Name
Or
或者
HttpContext.User.Identity.Name
What is the difference between these? As far as a I can tell within the MVC framework the controller has the current HttpContext stored as a property so these methods are identical. Is that correct?
这些有什么区别?据我所知,在 MVC 框架中,控制器将当前的 HttpContext 存储为一个属性,因此这些方法是相同的。那是对的吗?
回答by Lucero
Yes, they will usually be identical. However, if you're working with additional threads, they will not be; System.Web.HttpContext.Currentis threadstatic.
是的,它们通常是相同的。但是,如果您正在使用其他线程,则不会;System.Web.HttpContext.Current是线程静态的。
回答by Levi
The context provided by the controller (not the static HttpContext.Current) is mockable. If you're interested in unit-testing your code, it's generally far easier to create a mock ControllerContext and set it on the Controller than it is to go through HttpContext.Current. Otherwise ControllerContext.HttpContext points to the same data as HttpContext.Current.
控制器提供的上下文(不是静态 HttpContext.Current)是可模拟的。如果您有兴趣对代码进行单元测试,通常创建模拟 ControllerContext 并将其设置在控制器上要比通过 HttpContext.Current 容易得多。否则 ControllerContext.HttpContext 指向与 HttpContext.Current 相同的数据。

