问题
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