C#+.netFrameWork4.5.2+WebAPI+Jquery+Ajax跨域请求问题
mvc .net frameWork4.6.2优先这种方法
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<!--系统编码-->
<add key="SystemCode" value="56577edd-c6e1-ea11-80b7-8a4fa55a05cb" />
<!--Redis缓存队列-->
<add key="RedisQueue" value="sys_user_session" />
<!--Redis缓存数据库索引-->
<add key="RedisDbIndex" value="1" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime maxRequestLength="40960000" targetFramework="4.5.1" />
<customErrors mode="Off" defaultRedirect="404.html">
<error statusCode="404" redirect="404.html" />
<error statusCode="500" redirect="500.html" />
<error statusCode="401" redirect="401.html" />
</customErrors>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.2.10" newVersion="1.3.2.10" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="BouncyCastle.Crypto" publicKeyToken="0e99375e54769942" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.8.10.0" newVersion="1.8.10.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.1" newVersion="5.0.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.5.0" newVersion="4.5.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.Pipelines" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.9.0" newVersion="5.2.9.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="RestSharp" publicKeyToken="598062e77f915f75" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-106.15.0.0" newVersion="106.15.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<!--<staticContent>
<mimeMap fileExtension=".wasm" mimeType="application/wasm" />
</staticContent>-->
</system.webServer>
</configuration>
webAPI环境.net frameWork4.5.2
选中webAPI项目=》nuget包管理器=》输入microsoft.aspnet.webapi.cors=》安装
在webAPI controller控制器设置Cors ,并新建TestModel
//[EnableCors(origins: "*", headers: "Access-Control-Allow-Origin", methods: "GET,POST,PUT,DELETE,OPTION" [EnableCors("*", "*", "*")] public class TestController : ApiController { public string Post(TestModel text) { return "Post"; } }
在App_Start文件夹中的WebApiConfig.cs文件中注册Cors功能
public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); //config.EnableCors(); config.EnableCors(new EnableCorsAttribute("*", "*", "*") { SupportsCredentials=true }); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
注意如果报这个错has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
错误意思就是两个cros策略冲突了,WebApiConfig.cs文件中的Cors配置和Web.config文件中的Cors配置,把web.config文件中的Cors配置删掉即可,
前端页面代码
function aaa() { var aa = $('#aaa').val(); var bb = $('#bbb').val(); var testinfo = { "aa": aa, "bb": bb } //var your_object = JSON.parse(json_text); jQuery.support.cors = true; $.ajax({ url: 'http://localhost:00000/api/Test', type: 'POST', async: true, dataType: "json", //contentType: "application/x-www-form-urlencoded",//键值对传给后端 contentType: "application/json;charset=utf-8", //json格式传给后端 //data: { "plantCode": $plantCode, "tempPNs": $txtPN, "dateS": $dateS, "dateE": $dateE }, data: JSON.stringify(testinfo), //data: { a: 'zhangsan' }, success: function (data) { console.log(data), alert('请求成功') }, error: function (xhr) { console.log(), alert('请求失败') } }); }
启动调试
在post请求中打断点查看request传入数据,说明可以正常接收数据
浏览器F12调试,已成功接收数据,说明可以正常返回数据
注意:如果WebAPI发布环境是IISV5.2版本,甚至更老的版本,这种IIS对应得系统往往是WindowsServer2003R2或者WindowsServer2008等等的老版本服务器, 那你一定要小心了,如果以上你都配置好了,还是报Cors的错误,那很有可能是IIS不支持.netFramWork4.5.2
注意:如果还是出错,可能是你程序的web.config出错了,但是没报出来,最好的方法是发布一次,把预编译打上对勾,预编译可以把配置文件的错误找出来
注意:如果本地可以,发布到服务器还是报跨域的错,那你检查一下iis的沟都挑上了没有,通常以下三项选择就可以了
如果用户的电脑被限制了端口访问,比如只能访问80或者808,8080端口,那么即使你配置没有问题了,IIS版本也支持.netFrameWork4.5.2,任然不能请求成功,浏览器会报err-Connection错误,这是因为ajax请求数据本质上
并非在服务器去访问API再把数据传给客户端,而是从客户端访问API, 是不是感觉ajax一般般
关于Cors的策略请看微软官网解说: https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-3.1