C# 无法访问 HttpContext.Current
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18309239/
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
Can't access to HttpContext.Current
提问by Ema.H
I can't access to HttpContext.Current on my project MVC4 with C#4.5
我无法使用 C#4.5 在我的项目 MVC4 上访问 HttpContext.Current
I've added my reference to System.Web in my project and added the using instruction on my controller page...
我在我的项目中添加了对 System.Web 的引用,并在我的控制器页面上添加了 using 指令......
But I can access currentHandler only...
但我只能访问 currentHandler ......
var context = HttpContext.CurrentHandler; //Current
Is HttpContext.Current
deprecated on C#4.5 ?
HttpContext.Current
在 C#4.5 上被弃用了吗?
I've looked this help page : http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx
我看过这个帮助页面:http: //msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx
采纳答案by Darren
Have you included the System.Web
assembly in the application?
您是否已将System.Web
程序集包含在应用程序中?
using System.Web;
If not, try specifying the System.Web
namespace, for example:
如果没有,请尝试指定System.Web
命名空间,例如:
System.Web.HttpContext.Current
回答by Andrei
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
这是因为您指的是名为HttpContext
. 要访问当前上下文,请使用完整的类名:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
然而,强烈不建议在 ASP.NET MVC 中访问这样的上下文,所以是的,您可以认为System.Web.HttpContext.Current
在 ASP.NET MVC 中已被弃用。访问当前上下文的正确方法是
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
或者如果您在控制器内,只需使用成员
this.HttpContext
回答by Amir Syafrudin
Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVCapplications.
添加一点以减轻这里的混乱。尽管 Darren Davies(已接受)的答案更直接,但我认为 Andrei 的答案是MVC应用程序的更好方法。
The answer from Andrei means that you can use HttpContext
just as you would use System.Web.HttpContext.Current
. For example, if you want to do this:
Andrei 的回答意味着您可以HttpContext
像使用System.Web.HttpContext.Current
. 例如,如果您想这样做:
System.Web.HttpContext.Current.User.Identity.Name
you should instead do this:
你应该这样做:
HttpContext.User.Identity.Name
Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.
两者都实现了相同的结果,但(再次)就MVC 而言,更推荐后者。
Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.
可以在此处找到关于此问题的另一个很好且直接的信息:MVC ASP.NET 中的 HttpContext.Current 和 Controller.Context 之间的差异。