zoukankan      html  css  js  c++  java
  • 步步为营:Asp.Net客户端存Cookie服务端取

    function Cookies(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
    options = options || {};
    if (value === null) {
    value = '';
    options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
    var date;
    if (typeof options.expires == 'number') {
    date = new Date();
    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    } else {
    date = options.expires;
    }
    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    var path = options.path ? '; path=' + (options.path) : '/';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
    // Does this cookie string begin with the name we want?
    if (cookie.substring(0, name.length + 1) == (name + '=')) {
    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    break;
    }
    }
    }
    return cookieValue;
    }
    }

    这是一个存入Cookie和获取的函数

    调用:第一个参数键名,第二个参数值,第三个参数 路径和过期时间

    Cookies("val", str, { path: '/', expires: 10 });

    到了.Net里,因为我在后台写Cookie都是指定某个域下的,如果是要获取前台的path '/' 就不指定

    获取域中的Cookie

    /// <summary>
    /// 获得cookie值
    /// </summary>
    /// <param name="strName"></param>
    /// <returns></returns>
    public static string GetCookie(string strName)
    {
    if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies["shikee.com"] != null &&
        HttpContext.Current.Request.Cookies["shikee.com"][strName] != null)
    {
    return Utils.UrlDecode(HttpContext.Current.Request.Cookies["shikee.com"][strName].ToString());
    }

    return null;
    }

    不指定shikee.com域

    传入的strName就是JS传入的键名,这样就找到path为"/"下的Cookie

    public static string GetCookie_path(string strName)
    {
    if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
    {
    Encoding encoding = Encoding.GetEncoding("UTF-8");
    return HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value, encoding);
    }
    return null ;
    }







  • 相关阅读:
    .NET面试题系列[2]
    .NET面试题系列[1]
    被淡忘的c#析构函数
    关于Spring IOC容器解释
    工作随笔记 点击除div自身之外的地方,关闭自己
    js获得控件位置
    PHP如何判断对象为空的方法分享
    PHP 网页调用本地exe程序实例
    PHP jQuery实现上传图片时预览图片的功能实例
    Yii 自带的分页实例
  • 原文地址:https://www.cnblogs.com/79039535/p/2284855.html
Copyright © 2011-2022 走看看