C#/.NET 分布式专题(SOA【面向服务】WebApi解决跨域问题)

  1. negut引用:MIcrosoft.AspNet.WebApi.Cors
  2. 添加配置如下:webapi网站就可以解决跨域问题

全局配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));//全部都允许,
    }
}

方法配置

[EnableCors(origins: "http://localhost:9099/", headers: "*", methods: "GET,POST,PUT,DELETE")]
public Users GetUserByID()
{

}

行为特性配置跨域

public class CustomActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    }
}

注意点
jq跨域兼容处理

//microsoft.aspnet.webapi.cors
jQuery.support.cors = true;
var location = "http://localhost:8088";
$("#btnGetCors1").on("click", function () {
    $.ajax({ url: location + "/api/users/GetUserByID", type: "get", data: { "id": 1 }, success: function (data) { alert(data); }, datatype: "json" });
});
发布了143 篇原创文章 · 获赞 117 · 访问量 4235

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/103863783