Лучший способ определить, включены ли файлы cookie в ASP.NET?

StackOverflow https://stackoverflow.com/questions/210321

  •  03-07-2019
  •  | 
  •  

Вопрос

Каков наилучший способ определить, включены ли в браузере пользователя файлы cookie в ASP.NET?

Это было полезно?

Решение

Установите файл cookie, принудительно перенаправьте на какую-либо проверочную страницу и проверьте файл cookie.

Или установите файл cookie при каждой загрузке страницы, если он еще не установлен.Например, я предполагаю, что это делается для того, чтобы проверить, поддерживаются ли файлы cookie, чтобы при попытке входа в систему отображалось сообщение о том, что им необходимо включить файлы cookie.Установите для файла cookie входа значение по умолчанию для гостевых пользователей, если у них еще не установлен файл cookie.Затем на странице входа проверьте наличие файла cookie пользователя и, если он не установлен, отобразите свое сообщение.

Другие советы

@Мэттью прав, единственный способ узнать это — установить файл cookie, перенаправить его, а затем проверить.Вот функция C# для предварительной проверки, которую вы можете поместить в событие загрузки страницы:

private bool cookiesAreEnabled()
{
bool cookieEnabled = false;

if(Request.Browser.Cookies)
{
   //Your Browser supports cookies 
   if (Request.QueryString["TestingCookie"] == null)
   {
     //not testing the cookie so create it
     HttpCookie cookie = new HttpCookie("CookieTest","");
     Response.Cookies.Add(cookie);

     //redirect to same page because the cookie will be written to the client computer, 
     //only upon sending the response back from the server 
     Response.Redirect("Default.aspx?TestingCookie=1")
   }
   else
   {
     //let's check if Cookies are enabled
      if(Request.Cookies["CookieTest"] == null)
      {
        //Cookies are disabled
      }
      else
      {
        //Cookies are enabled
        cookieEnabled = true;
      }   
   }

}
else
{
  // Your Browser does not support cookies
}
return cookieEnabled;
}


Вы также можете сделать это в javascript следующим образом:

function cookiesAreEnabled()
{   
    var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0;  

    if (typeof navigator.cookieEnabled == "undefined" && cookieEnabled == 0){   
    document.cookie="testcookie";   
    cookieEnabled = (document.cookie.indexOf("test­cookie") != -1) ? 1 : 0; 
    }   

  return cookieEnabled == 1;
}

Напишите файл cookie, перенаправьте, посмотрите, сможете ли вы прочитать файл cookie.

Что ж, я думаю, если мы сможем сохранить cookie в начале сеанса Global.ASAX и прочитать это на странице..разве это не лучший способ?

Функция С# meda работает, хотя вам придется изменить строку:

HttpCookie cookie = новый HttpCookie("","");

к

HttpCookie cookie = новый HttpCookie("CookieTest", "CookieTest");

По сути то же решение, что и meda, но в VB.NET:

Private Function IsCookieDisabled() As Boolean
    Dim currentUrl As String = Request.RawUrl
    If Request.Browser.Cookies Then
        'Your Browser supports cookies 
        If Request.QueryString("cc") Is Nothing Then
            'not testing the cookie so create it
            Dim c As HttpCookie = New HttpCookie("SupportCookies", "true")
            Response.Cookies.Add(c)
            If currentUrl.IndexOf("?") > 0 Then
                currentUrl = currentUrl + "&cc=true"
            Else
                currentUrl = currentUrl + "?cc=true"
            End If
            Response.Redirect(currentUrl)
        Else
            'let's check if Cookies are enabled
            If Request.Cookies("SupportCookies") Is Nothing Then
                'Cookies are disabled
                Return True
            Else
                'Cookies are enabled
                Return False
            End If
        End If
    Else
        Return True
    End If
End Function

Вы также можете проверить стоимость Request.Browser.Cookies.Если это правда, браузер поддерживает файлы cookie.

это лучший способ

взято изhttp://www.eggheadcafe.com/community/aspnet/7/42769/cookies-enabled-or-not-.aspx

function cc()
{
 /* check for a cookie */
  if (document.cookie == "") 
  {
    /* if a cookie is not found - alert user -
     change cookieexists field value to false */
    alert("COOKIES need to be enabled!");

    /* If the user has Cookies disabled an alert will let him know 
        that cookies need to be enabled to log on.*/ 

    document.Form1.cookieexists.value ="false"  
  } else {
   /* this sets the value to true and nothing else will happen,
       the user will be able to log on*/
    document.Form1.cookieexists.value ="true"
  }
}

спасибо Венкату К.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top