问题描述:
google插件跨域请求WebApi相关解决方案
1.ajax解决含登录用户信息
$.ajax({ url: url, type: "POST", timeout: 60000, async: async, data: params, dataType: "json", xhrFields: { withCredentials: true }, crossDomain: true, //注意这两行代码,这里包含跨域并且包含登录用户信息 success: function (data) { call(data); }, error: function (error) {//增加访问出错信息返回 alert(JSON.stringify(error)); }, complete: function (XMLHttpRequest, status) { } });
2.解决WebApi跨域的问题
WebApi中的设置:
using System.Web.Http.Cors;//引用
[EnableCors(origins: "*", headers: "*", methods: "*")]//注意在类上添加
public class DemoController : ApiController
{
[Route("api/GatherOne"),HttpPost]
public HttpResponseMessage DemoCors()
{
IEnumerable<string> origin; Request.Headers.TryGetValues("Origin", out origin);//注意这里:获取前端的Origin值 if (origin.Any()) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); httpResponseMessage.Headers.Add("Access-Control-Allow-Origin", origin);//这里必须要添加此标签中,否则无法解决跨域的问题 httpResponseMessage.Headers.Add("Access-Control-Allow-Headers", "*"); httpResponseMessage.Headers.Add("Access-Control-Allow-Credentials", "true"); httpResponseMessage.Headers.Add("Access-Control-Allow-Methods", "*");
}
}
3.WebApi中获取前端headers中的值
IEnumerable<string> origin; Request.Headers.TryGetValues("Origin", out origin);//获取Origin的值