• .net webapi跨域无法获取cookie问题解决办法


    1.首先webapi要设置允许跨域

    /// <summary>
        ///     同源策略
        /// </summary>
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
        public sealed class CorsPolicyAttribute : Attribute, ICorsPolicyProvider
        {
            /// <summary>
            ///     同源策略
            /// </summary>
            private readonly CorsPolicy _Policy;
    
            public CorsPolicyAttribute()
            {
                _Policy = new CorsPolicy
                {
                    AllowAnyMethod = true,
                    AllowAnyHeader = true,
                    AllowAnyOrigin = true,
                    PreflightMaxAge = 60*60*6
                };
                _Policy.SupportsCredentials = true; // 这个不能使用True。User跨域问题处理
                _Policy.Headers.Add("*");
                _Policy.Methods.Add("*");
                //_Policy.Origins.Add(PubConstant.CorsUrl);
                _Policy.Origins.Add("*");
            }
    
    
            public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                return Task.FromResult(_Policy);
            }
        }

    2.API控制器增加同源策略标注

    /// <summary>
        /// 基础控制器
        /// </summary>
        [CorsPolicy]
        [AuthFilter]
        public class BaseApiController : ApiController

    3.存储信息到cookie,注意设置Domain

    public static void SetUserIdCookie(HttpResponseMessage response, string userId)
            {
    
                var expiresDay = 7;
    
                var cookies = new List<CookieHeaderValue>();
                
                //string stryqurc = string.Format(CultureInfo.InvariantCulture, "ricky.{0}",  FunHelper.GetMarkByUserId(userId));
                var newCookie2 = new CookieHeaderValue(UCGlobalDefine.IDCookieName, userId)
                {
                    Domain = "user.17track.net", //这个是api的域名
                    Path = "/",
                    Expires = DateTimeOffset.Now.AddDays(expiresDay)
                };
                cookies.Add(newCookie2);
                response.Headers.AddCookies(cookies);
            }
    
    //response在控制器中创建:
    var response = Request.CreateResponse(HttpStatusCode.OK, result);

    3.webapi获取cookie方法

    public static string GetCookie(HttpRequestMessage request,string cookieName)
            {
                //var cookies = request.Headers.GetCookies()?.FirstOrDefault();
                var cookieList = request.Headers.GetCookies();
                var cookies = cookieList?.FirstOrDefault();
                string uid = string.Empty;
                if (cookies?[cookieName] != null)
                {
                    uid = cookies[cookieName]?.Value;
                }
                return uid;
            }

    4.前端ajax访问,注意设置withCredentials

    //获取当前用户
    Ricky.GetUser = function () {
        $.ajax({
            type: "get",
            url: Ricky.Api.GetUser,
            dataType: "json",
            async: false,
            xhrFields: {
                withCredentials: true
            },
            success: function (result) {
                if (result.Code == 0) {
                    LoginUser = result.Json;
                }
                else if (result.Code == -3) {
                    layer.msg(result.Message);
                    top.location.href = "login.html";
                }
                else {
                    layer.msg(result.Message);
                }
            },
            error: function () {
                layer.msg("登录信息异常");
            }
        });
    };
  • 相关阅读:
    常用数据分析方法及分析工具,比如:EXCEL、SAS、SPSS
    常用代码管理工具,如git、hg、svn
    Memcached分布式内存对象缓存系统
    10个出色的NoSQL数据库
    虚拟机
    使用自己的CSS框架(转)
    响应式设计,bootstrap框架的IE兼容问题
    区别ie8和ie9的方法
    焦点问题onfocus=”this.blur()”代替方法(转)
    php 引用其他action中的方法
  • 原文地址:https://www.cnblogs.com/CuiRicky/p/10808117.html
Copyright © 2020-2023  润新知