为什么Request.Cookies为null? [英] Why is Request.Cookies null?

查看:3025
本文介绍了为什么Request.Cookies为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我运行的另一个线程的后续操作,它是在c#中读取Cookie 。然而,在那篇文章中的答案似乎在布什周围,所以我想简化我的问题。我认为,回答这个,我将能够解决这个问题。



这行可能会导致NullReferenceException:

  HttpCookie aCookie = Request.Cookies [UserSettings]; 

我相信一个名为UserSettings的cookie是存在的,我可以看到它与开发者工具栏。
所以Request或者Request.Cookies必须是null,对吗?



为什么我不能使用Request.Cookies?

编辑:在index.aspx中添加了cookie创建代码,我试图阅读

 < 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)+
(type of cexpire =='date'?'expires ='+ cexpire.toGMTString():'')+
',path = /;';
}
< / script>


解决方案

这不是添加cookie的地方。当你谈论用户设置时,它不是添加cookie的地方。用户设置通常在用户的动作时建立,例如。用户单击德语链接以切换到德语设置。这是在这个控制器方法中,事件,或者您的应用程序正在处理应该将Cookie设置为响应并建立其持久性的点击行为。



记住几件事。在此方法中,您要将此Cookie添加到每个响应。在随后的控制器调用 hc.getLang()中,您正在访问从Cookie中检索语言的请求。在第一次调用中,这将始终为null,因为cookie不存在于请求中。你只是将它添加到响应。然而,在下一次调用时,Cookie应该存在,但它将始终以设置为nl的语言存在,因为您强制使用每个请求



我建议你把这个global.asax事件的cookie生成代码放在一个页面,使用一个接口来设置它(一个链接,一个按钮,任何)。然后你的控制器将从那一点访问请求cookie。请务必记住,在网页的生命周期中,请求和响应是完全不同的对象,无论是网页表单还是mvc。



编辑:
因为你提到使用控制器,我假设你使用MVC,所以我将目标我的代码示例工作。因为确定在 Application_BeginRequest 中设置cookie是不好的魔法,所以您需要在应用程序中的某个其他点参考用户操作来建立它。让我们假设你有一个控制器 SettingsController ,它有一个动作 SetLanguage

  [Authorize] 
public class SettingsController:Controller
{

// ...跳过其他构造函数和方法代码

[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);
}

}

写入以从模型中获取 AssignedLanguage 属性,并使用它来确定即时请求的语言。然而,所有后续请求都应该具有UserSettings cookie的访问权限。此时,您应该能够在后续请求的请求管道中的任何位置调用 Request.Cookies [UserSettings]


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>

解决方案

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.

这篇关于为什么Request.Cookies为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆