代码改变世界

webapi 跨域解决方案

2016-09-07 11:03  莫球名堂  阅读(267)  评论(0编辑  收藏  举报

方法1.添加节点

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

方法2.添加一个过滤器,在需要跨域的接口上添加属性:

//创建过滤器
public class CrossSiteAttribute : ActionFilterAttribute
{
        private const string Origin = "Origin";
        private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        private const string originHeaderdefault = "*";
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeaderdefault);
        }
}

//添加属性
[CrossSite]
public string Get(int id)
{
      string result = "{\"name\":\"zhangsan\",\"date\":\"2012-12-03\"}";
      return result;
}

3.调用

<script>
        $.ajax({
            type: 'GET',
            url: 'http://localhost:3786/api/Values/Get?id=1',
            dataType: 'JSON',
            success: function (data) {
                alert(data);
            }
        });
</script>