come controllare biscotto abilitato per il browser o non in ASP.NET (MVC)come controllare biscotto abilitato per il browser o no
6
A
risposta
0
come ho fatto che:
fare un cookie speciale durante il login, aggiungi? cookiecheck = true nell'URL e, vedendo cookiecheck nell'url, controlla se esiste un cookie speciale per il controllo. in caso contrario, i cookie sono disabilitati.
11
Ecco il mio filtro di autorizzazione sulla mia metodo di azione login:
/// <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)
{
}
}
Si può usare per fare in modo che i cookie siano abilitati come
[EnsureCookies]
[HandleError(ExceptionType = typeof(CookiesNotEnabledException), View="NoCookies")]
public ActionResult LogOn(....) ...
o fare in modo che un cookie specifico è stato impostato per un'azione
[EnsureCookies("MyCookie")]
[HandleError(ExceptionType = typeof(CookiesNotEnabledException), View="Some cookie not set view"]
public ActionResult ActionThatNeedsMyCookie()....
Non sono sicuro del motivo per cui avresti mai avuto bisogno di farlo, ma ci sono S. Spero che sia utile.
Problemi correlati
- 1. C# WebRequest utilizzando browser web biscotto
- 2. Controllare utente apre il sito in App o no
- 3. Come verificare che il JavaScript del browser sia abilitato o meno
- 4. Controllare valore immesso è il numero o no
- 5. Come controllare se l'array di byte è vuoto o no?
- 6. Come controllare l'indirizzo di posta elettronica esiste o no?
- 7. Come controllare la directory esistente o no in linux.?
- 8. Come controllare il firewall della finestra è abilitato o meno usando i comandi
- 9. controllare o disabilitare browser pulsante Indietro con Javascript o AngularJS
- 10. Golang: come seguire posizione con il biscotto
- 11. Come controllare i browser installati usando C# per i principianti
- 12. Veloce modo falsato-veritiero di controllare IE o no?
- 13. Come posso controllare in sicurezza il nodo vuoto o no? (Symfony 2 Crawler)
- 14. angolare 2: Controllare se il browser dell'utente è compatibile
- 15. Come controllare a livello di programmazione se l'hotspot è abilitato o disabilitato?
- 16. Come possiamo verificare se la compressione gzip/deflate ha funzionato nei browser IE o no?
- 17. un biscotto - più pagine
- 18. Come controllare il browser per il supporto touchstart usando JS/jQuery?
- 19. Test per biscotto esistenza in Django
- 20. Trova MPMoviePlayerController suona o no
- 21. Come verificare se NFC è abilitato o meno in Android?
- 22. Come controllare il secondario è ora sincronizzato o meno
- 23. Rileva un'applicazione installata o no?
- 24. Utilizzo della classe .no-js per il rilevamento di js
- 25. Controllare la cache del browser per un file js
- 26. Trova localmente il supporto GPS del dispositivo o no?
- 27. Il puntatore "questo" è abilitato per RTTI?
- 28. Android convertView, per usarlo o no?
- 29. Per utilizzare l'oggetto attivo o no?
- 30. iOS: come posso controllare se una stringa è numerica o no?
Soluzione piacevole; anche se sarebbe bello se il gestore delle eccezioni tentasse di impostare il cookie e lo leggesse di nuovo. Prevenire i loop sarebbe importante .. – LamonteCristo
Ciao! Ho ottenuto il tuo codice e quindi ho Execption qui: 'if (noCookie) lancia CreateNotEnabledException();' Come gestirlo? – user3818229
Devo sovrascrivere il metodo OnExecption? – user3818229