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("登录信息异常");
        }
    });
};