Why is Request.Cookies null?

妖精的绣舞 提交于 2020-01-16 12:03:50

问题


This is a follow-up on another thread I have running which is Reading cookie in c# . However, the answers in that post seem to beat around the bush so I want to simplify my question here. I think that answering this, I'll be able to solve that problem. Stuck almost two days now trying to read a cookie so any help is appreciated.

What could cause a NullReferenceException at this line:

HttpCookie aCookie = Request.Cookies["UserSettings"];

I am sure a cookie called "UserSettings" is there, as I can see it with developer toolbar. So Request or Request.Cookies must be null, right?

Why can't I use Request.Cookies? Every single cookie tutorial I look at does it like that.

EDIT: added cookie creation code in index.aspx, btw im trying to read the cookie in HomeController.cs, dont know if this matters, but thought id mention it.

<script type="text/javascript">
    function setLanguage() {
    cname = "language";
    cvalue =           document.getElementById('language').options[document.getElementById('language').selectedInd    ex].value;
    cexpire = new Date();
    cexpire.addDays(1);
    document.cookie = cname + '=' + escape(cvalue) +
(typeof cexpire == 'date' ? 'expires=' + cexpire.toGMTString() : '') +
',path=/;';
}
</script>

回答1:


This is not the place for cookie addition. It is especially not the place for cookie addition when you're talking about a user setting. A user setting is usually established at the action of a user, e.g. a user clicks the German language link to switch to the German settings. It is in this controller method, event, or however your application is handling that click behavior that should be setting the cookie into the response and establishing its persistence.

Also, keep in mind a couple of things. In this method, you're adding this cookie to every response. In the subsequent controller call hc.getLang() you are accessing the request to retrieve the language from the cookie. In the very first call this will ALWAYS be null because the cookie doesn't live in the request yet. You only just added it to the response. On the next call however, the cookie should exist, but it will always exist with the language set at "nl" because you're forcing it for every request.

I would recommend you take the cookie generation code out of this global.asax event and place it in a page that uses an interface to set it (a link, a button, whatever). Then your controller will have access from that point on to the request cookie. Always keep in mind that the request and response are completely separate objects during the lifecycle of a page regardless of whether it's webforms or mvc.

Edit: Because you mention using a controller, I'm assuming you're using MVC so I'll target my code sample to work in that vein. Since it's established that setting the cookie in the Application_BeginRequest is bad magic, you need to establish it at some other point in the application in reference to a user action. Let's assume you have a controller called SettingsController and it has an action called SetLanguage.

[Authorize]
public class SettingsController : Controller
{

    // ... skipping other constructor and method code

    [Authorize]
    [HttpPost]
    public ActionResult SetLanguage(MyLanguageModel model)
    {
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie.Value = model.AssignedLanguage;
        myCookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(myCookie);

        return View(model);
    }

}

This would assume that the view is written to grab the AssignedLanguage property from the model and use it to determine the language for the immediate request. All subsequent requests, however, should have access to the UserSettings cookie. At this point, you should be able to call Request.Cookies["UserSettings"] from anywhere within the request pipeline on subsequent requests.



来源:https://stackoverflow.com/questions/11031243/why-is-request-cookies-null

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