C# 如何访问 ASP.NET MVC 控制器中的 Request.cookies?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/716636/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:19:14  来源:igfitidea点击:

How do I access Request.cookies in an ASP.NET MVC controller?

c#asp.net-mvc

提问by ANIL MANE

I'm trying to get a user ID stored in cookies via a common Controller file, which I can access throughout the site.

我正在尝试通过一个公共控制器文件获取存储在 cookie 中的用户 ID,我可以在整个站点中访问该文件。

I have created FunctionsControlleras a controller, with content as follows:

我创建FunctionsController了一个控制器,内容如下:

public static int loggedinUser()
{
    return Convert.ToInt32(  request.Cookies["userid"].Value);
}

I am unable to request any cookie items even if I tried with:

即使我尝试过,我也无法请求任何 cookie 项目:

HttpRequestBase request = controllerContext.HttpContext.Request;

回答by Ian Suttle

I don't have a problem accessing cookies in ASP.NET MVC using a standard access statement such as:

我使用标准访问语句访问 ASP.NET MVC 中的 cookie 没有问题,例如:

Request.Cookies["someCookie"]

Your sample had a lower-cased "r" in "request.Cookies". Could that be your problem?

您的示例在“request.Cookies”中有一个小写的“r”。那可能是你的问题吗?

回答by ilivewithian

Remove the staticpart of your method declaration and then use Request.Cookies["userId"]

删除static方法声明的一部分,然后使用Request.Cookies["userId"]