Is there any difference between HttpContext.Current.Request and HttpContext.Request?

我怕爱的太早我们不能终老 提交于 2021-02-18 08:38:52

问题


If I want to access Request object in controller action I need to write HttpContext.Request, whereas if I want to access the same object in MVC view, I need to write HttpContext.Current.Request. Is there any difference between them? The problem I am facing is that, the cookies which I set through HttpContext.Response.Cookies.Add in controller action are not being retrieved in HttpContext.Current.Request.Cookies collection in an MVC view, though I can see those cookies through javascript.


回答1:


The reason you have to write HttpContext.Request in a controller and HttpContext.Current.Request on a view is because a controller that you write inherits the abstract class Controller that has a property called HttpContext that is of type HttpContextBase. The view then uses the sealed class HttpContext that gives you an httpcontext object for the current request.

Is there any difference between them?

No. As both give you the same HttpRequest object for the current request.




回答2:


Unless i'm mistaken, you write a cookie out to the response, but that cookie is not available on the request until the next request is made (ie, you have to load the same or a new page again to get it to read the cookie). Cookies are not a good way to share information between controller and view, you should use ViewData or ViewBag.

Also, you must make sure that you are not writing to the cookie after you have already output anything, which is one reason that Response.Write is not recommended.

The reason the javascript works is that it reads the cookie at the client rather than on the server.



来源:https://stackoverflow.com/questions/16060632/is-there-any-difference-between-httpcontext-current-request-and-httpcontext-requ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!