如何检查的cookie启用浏览器或不 [英] how to check cookie enabled for the browser or not

查看:314
本文介绍了如何检查的cookie启用浏览器或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查浏览器或不ASP.NET(MVC)启用的cookie

how to check cookie enabled for the browser or not in ASP.NET (MVC)

推荐答案

下面是我的授权过滤器对我的登录操作方法:

Here's my authorization filter on my login action method:

/// <summary>
/// Ensures that cookies are enabled.
/// </summary>
/// <exception cref="CookiesNotEnabledException" />
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class EnsureCookiesAttribute : FilterAttribute, IAuthorizationFilter
{
    private readonly string _cookieName;
    private readonly bool _specificCookie;

    /// <summary>
    /// The name of the cookie to use to ensure cookies are enabled.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible",
        Justification = "Field is public so that the default value may be modified.")]
    public static string DefaultCookieName = "SupportsCookies";

    public const string CookieCheck = "cookieCheck";

    /// <summary>
    /// Checks to make sure cookies are generally enabled.
    /// </summary>
    public EnsureCookiesAttribute() : this(null) { }

    /// <summary>
    /// Checks to make sure a cookie with the given name exists
    /// </summary>
    /// <param name="cookieName">The name of the cookie</param>
    public EnsureCookiesAttribute(string cookieName)
    {
        if (String.IsNullOrEmpty(cookieName))
        {
            cookieName = DefaultCookieName;
        }
        else
        {
            _specificCookie = true;

        }

        QueryString = CookieCheck;

        _cookieName = cookieName;
    }

    /// <summary>
    /// The name of the cookie to check for.
    /// </summary>
    public string CookieName
    {
        get { return _cookieName; }
    }

    /// <summary>
    /// The querystring parameter to use to see if a test cookie has been set.
    /// </summary>
    public string QueryString { get; set; }

    protected static CookiesNotEnabledException CreateBrowserException()
    {
        return new CookiesNotEnabledException("Your browser does not support cookies.");
    }

    protected static CookiesNotEnabledException CreateNotEnabledException()
    {
        return new CookiesNotEnabledException("You do not have cookies enabled.");
    }

    #region Implementation of IAuthorizationFilter

    /// <summary>
    /// Called when authorization is required.
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"
        , Justification = "Should swallow exceptions if a cookie can't be set.  This is the purpose of the filter.")]
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        var request = filterContext.HttpContext.Request;
        var response = filterContext.HttpContext.Response;

        if (!request.Browser.Cookies)
            throw CreateBrowserException();

        string currentUrl = request.RawUrl;

        var noCookie = (request.Cookies[CookieName] == null);
        if (!_specificCookie && noCookie && request.QueryString[QueryString] == null)
        {
            try
            {
                // make it expire a long time from now, that way there's no need for redirects in the future if it already exists
                var c = new HttpCookie(CookieName, "true") {Expires = DateTime.Today.AddYears(50)};
                response.Cookies.Add(c);

                currentUrl = currentUrl + (currentUrl.Contains('?') ? "&" : "?") + QueryString + "=true";

                filterContext.Result = new RedirectResult(currentUrl);
                return;
            }
            catch
            {
            }
        }

        if (noCookie)
            throw CreateNotEnabledException();
    }

    #endregion
}

/// <summary>
/// Thrown when cookies are not supported.
/// </summary>
[Serializable]
public class CookiesNotEnabledException : HttpException
{
    public CookiesNotEnabledException()
    {
    }

    protected CookiesNotEnabledException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }

    public CookiesNotEnabledException(string message)
        : base(message)
    {
    }

    public CookiesNotEnabledException(string message, Exception innerException)
        : base(message, innerException)
    {
    }
}

您可以用它来确保饼干作为

You can use it to make sure that cookies are enabled as

[EnsureCookies]
[HandleError(ExceptionType = typeof(CookiesNotEnabledException), View="NoCookies")]
public ActionResult LogOn(....) ...

或确保特定的Cookie已经为一个动作集

or to make sure that a specific cookie has been set for an action

[EnsureCookies("MyCookie")]
[HandleError(ExceptionType = typeof(CookiesNotEnabledException), View="Some cookie not set view"]
public ActionResult ActionThatNeedsMyCookie()....

我不知道为什么你会永远需要做的,但它是。希望它的帮助。

I'm not sure why you'd ever need to do that, but there it is. Hope its helpful.

这篇关于如何检查的cookie启用浏览器或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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