如何检测ASP.Net MVC 5中是否启用了浏览器cookie?

时间:2017-11-16 03:37:06

标签: asp.net asp.net-mvc cookies

如果在客户端的浏览器中禁用了cookie,我将在我的ASP.Net MVC应用程序中检测到。我的所有搜索结果都是带有Page_Load等的asp.net WebForms,而不是ASP.Net MVC应用程序。

如何在服务器端检测是否启用了浏览器cookie?

2 个答案:

答案 0 :(得分:1)

控制器代码:

public ActionResult Index()
        {
            var browser = Request.Browser;
            string s = "Browser Capabilities\n"
                       + "Type = " + browser.Type + "\n"
                       + "Name = " + browser.Browser + "\n"
                       + "Version = " + browser.Version + "\n"
                       + "Major Version = " + browser.MajorVersion + "\n"
                       + "Minor Version = " + browser.MinorVersion + "\n"
                       + "Platform = " + browser.Platform + "\n"
                       + "Is Beta = " + browser.Beta + "\n"
                       + "Is Crawler = " + browser.Crawler + "\n"
                       + "Is AOL = " + browser.AOL + "\n"
                       + "Is Win16 = " + browser.Win16 + "\n"
                       + "Is Win32 = " + browser.Win32 + "\n"
                       + "Supports Frames = " + browser.Frames + "\n"
                       + "Supports Tables = " + browser.Tables + "\n"
                       + "Supports Cookies = " + browser.Cookies + "\n"
                       + "Supports VBScript = " + browser.VBScript + "\n"
                       + "Supports JavaScript = " +
                       browser.EcmaScriptVersion.ToString() + "\n"
                       + "Supports Java Applets = " + browser.JavaApplets + "\n"
                       + "Supports ActiveX Controls = " + browser.ActiveXControls
                       + "\n"
                       + "Supports JavaScript Version = " +
                       browser["JavaScriptVersion"] + "\n";


            ViewBag.Message = s;
            return View();
        }

你可以在视图中使用:

<h3>@ViewBag.Message</h3>

答案 1 :(得分:1)

下面的代码可以在asp.net MVC

中使用

第1步:如果不存在则创建Cookie

public ActionResult CreateCookie()
{

  //Check if cookie Enabled on Page Load
  if (Request.Cookies["UserInfo"] != null)
  {
    // Cookie is enabled 
    // TODO , write your code
  }           
  else
  {
    // Create a new cookie, if cookie is null

    HttpCookie userCookie = new HttpCookie("UserInfo");
    userCookie["Name"] = "example";
    userCookie["Company"] = "example";
    userCookie.Expires.AddDays(50); // cookie will expire after 50 days
    Response.Cookies.Add(userCookie);

    return RedirectToAction("CookieEnabled");

 }

   return View();
}

第2步:检查Cookie是否已启用

public ActionResult CookieEnabled()
{
    if (Request.Cookies["UserInfo"] != null)
    {
        // Cookie is enabled 
        // TODO , write your code
    }

    else
    {
        // Cookie is disabled 
        // TODO , write your code
    }

    return View();
}

注意:您也可以使用JavaScript在客户端进行检查,查看this文章。