分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

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

发布时间:2023-09-06 02:18责任编辑:顾先生关键词:配置跨域

在项目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.NET\Framework\v4.0.30319\aspnet_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.NET\Framework64\v4.0.30319\aspnet_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();
???????????}
???????}

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

原文地址:https://www.cnblogs.com/miao817/p/9811730.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved