• webapi 跨域解决方案


    方法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>
  • 相关阅读:
    FastAdmin Shopro商城安装
    MYSQL ERROR 10060
    宝塔命令
    kdevtmpfsi挖矿病毒处理
    VUE安装
    原生JS请求(AJAX)
    Bootstrap: 模态框组件
    Bootstrap: 缩略图组件
    Bootstrap: 栅格系统
    Bootstrap: 下拉菜单组件 & 分页组件
  • 原文地址:https://www.cnblogs.com/yanjc/p/5848650.html
Copyright © 2020-2023  润新知