asp.net-mvc – 如何检查是否为浏览器启用了cookie
发布时间:2020-12-15 20:25:18 所属栏目:asp.Net 来源:网络整理
导读:如何在ASP.NET(MVC)中检查是否为浏览器启用了cookie 解决方法 这是我的登录操作方法的授权过滤器: /// summary/// Ensures that cookies are enabled./// /summary/// exception cref="CookiesNotEnabledException" /[AttributeUsage(AttributeTargets.Clas
|
如何在ASP.NET(MVC)中检查是否为浏览器启用了cookie
解决方法
这是我的登录操作方法的授权过滤器:
/// <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)
{
}
}
您可以使用它来确保启用cookie [EnsureCookies] [HandleError(ExceptionType = typeof(CookiesNotEnabledException),View="NoCookies")] public ActionResult LogOn(....) ... 或确保为某个操作设置了特定的Cookie [EnsureCookies("MyCookie")]
[HandleError(ExceptionType = typeof(CookiesNotEnabledException),View="Some cookie not set view"]
public ActionResult ActionThatNeedsMyCookie()....
我不确定你为什么需要那样做,但确实如此.希望它有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 基本MVC:“modelItem =>”做什么?
- asp.net – MVC 3中的SessionState属性是否正常工作?
- asp.net – 您使用什么工具来提高编码效率和整体效率
- Asp.Net Core 发布和部署( MacOS + Linux + Nginx )
- ASP.NET 实现Replace忽略大小写替换
- asp.net-web-api – ASP.NET核心WebAPI 404错误
- asp.net – 如何在设计模式下打开RDLC
- asp.net – 会话状态在此上下文中不可用
- asp.net-mvc – 动作过滤器执行顺序
- asp.net-mvc – Jasmine在一个单独的测试项目中
推荐文章
站长推荐
- asp.net-mvc – ASP.NET MVC应用程序中丰富的UI可
- asp.net – 对框架程序集“System.Runtime,Versi
- asp.net – 可能添加MIME类型到web.config而不可
- asp.net-mvc – IdentityServer MVC令牌过期
- asp.net-mvc – ASP.Net MVC中的线程安全性
- asp.net – 如何从FormCollection中获取复选框值
- asp.net-mvc – Web Essentials浏览器链接在Visu
- asp.net – 未捕获错误:在初始化之前无法在弹出
- asp.net-mvc – 在内部OnException(ExceptionCon
- asp.net-mvc-3 – MVC3值不能为null 参数名称:值
热点阅读
