.Net Core Api 运行跨域访问

2018/07/02 321

更改cookie策略

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.SlidingExpiration = true;
    // 必须关闭HttpOnly,不然js获取不到身份验证cookie
    options.Cookie.HttpOnly = false;
	// 动态获取domain,测试与生产环境domain不一样
    options.Cookie.Domain = Configuration["CookieDomain"]; 
	// api不需要跳转,返回401和提示就可以了
    options.Events.OnRedirectToLogin = async context =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
        context.HttpContext.Response.ContentType = "application/json; charset=utf-8";
        string json = JsonConvert.SerializeObject(HttpBaseResult.Unauthorized, jsonSerializerSettings);
        await context.HttpContext.Response.WriteAsync(json, Encoding.UTF8);
    };
});
	

配置中间件

app.UseCors(builder => builder.WithOrigins("http://localhost:4200", "https://doghappy.wang","http://www.doghappy.wang")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());
			

治疗接口洁癖

app.UseStatusCodePages(async context =>
{
    context.HttpContext.Response.ContentType = "application/json; charset=utf-8";
    HttpBaseResult result = null;
    switch (context.HttpContext.Response.StatusCode)
    {
        case StatusCodes.Status401Unauthorized:
            result = HttpBaseResult.Unauthorized;
            break;
        case StatusCodes.Status404NotFound:
            result = HttpBaseResult.NotFound;
            break;
        case StatusCodes.Status500InternalServerError:
            result = HttpBaseResult.InternalServerError;
            break;
    }
    if (result != null)
    {
        string content = JsonConvert.SerializeObject(result, jsonSerializerSettings);
        await context.HttpContext.Response.WriteAsync(content, Encoding.UTF8);
    }
});
	

全局的SerializerSettings

jsonSerializerSettings = new JsonSerializerSettings
{
     ContractResolver = new CamelCasePropertyNamesContractResolver()
};
评论