• .net跨域接口服务器端配置


    在项目Config文件中添加一下节点配置

    <system.webServer>
    <httpProtocol>
    <customHeaders>
    <add name="X-Content-Type-Options" value="nosniff"/>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Accept, Authorization, X-Request-With" />
    <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />
    </customHeaders>
    </httpProtocol>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>

    在global.cs文件中添加一下方法

    在ajax对webapi进行CORS跨域访问过程中,如果自定义header,浏览器会发出一个options的请求。

    询问浏览器是否支持自定义的header类型。

    webapi需要做如下处理,才能正常返回浏览器请求

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    var res = HttpContext.Current.Response;
    var req = HttpContext.Current.Request;

    //自定义header时进行处理
    if (req.HttpMethod == "OPTIONS")
    {
    res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie");
    res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
    res.StatusCode = 200;
    res.End();
    }
    }

  • 相关阅读:
    使用init_connect记录MySQL登录日志
    MySQL 在线开启GTID的每个阶段是要做什么
    chrome控制台发送post请求
    口语练习
    adb_usb.ini在adb找不到设备时
    ubuntu 12.04硬盘分区,格式化,挂载
    编译错误处理noproguard.classeswithlocal.dex已杀死
    ubuntu 12.04(gcc降级)编译android代码遇到"_FORTIFY_SOURCE"的解决方法
    ubuntu在update的时候报错GPL ERROR
    工作站环境搭建
  • 原文地址:https://www.cnblogs.com/miao817/p/9811730.html
Copyright © 2020-2023  润新知