使用Ajax调用ASMX API时遇CORS错误:缺少Access-Control-Allow-Origin头
Hey there, let's break down why you're hitting this CORS error and how to fix it quickly:
The Core Mistake in Your Frontend Code
You added Access-Control-Allow-Origin and Access-Control-Allow-Headers to your request headers—but those are supposed to be response headers sent from the server to the browser. The browser checks if the server includes these headers in its response to allow cross-origin access; sending them from the frontend does nothing to resolve the issue.
First, update your Ajax code to remove those unnecessary headers:
$.ajax({ url: '你的ASMX接口地址', type: "POST", crossDomain: true, dataType: "xml", contentType: "text/xml; charset=utf-8", // Remove the headers section entirely—you don't need it here data: soapXMLData, success: function (data) { alert("webmethod call success"); }, error: function (err) { alert("webmethod call failed"); } });
Server-Side Fixes for ASMX (The Real Solution)
CORS is enforced by the browser, so you need to configure your ASMX server to return the required CORS headers. Here are the most reliable methods:
1. Global Configuration via Web.config (Recommended)
Add these settings to your Web.config file under the <system.webServer> node. This applies CORS rules to all your ASMX endpoints:
<system.webServer> <httpProtocol> <customHeaders> <!-- Replace with your frontend origin (http://localhost:XXXXX) or use "*" for all (not recommended for production) --> <add name="Access-Control-Allow-Origin" value="http://localhost:XXXXX" /> <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> </system.webServer>
- The
OPTIONSmethod is critical here because browsers send a preflight OPTIONS request before your actual POST request to check CORS permissions.
2. Per-WebMethod Configuration with Attributes
If you only want to enable CORS for specific WebMethods, install the Microsoft.AspNet.WebApi.Cors NuGet package, then add the [EnableCors] attribute to your method:
using System.Web.Http.Cors; [WebMethod] [EnableCors(origins: "http://localhost:XXXXX", headers: "*", methods: "*")] public string YourWebMethodName() { // Your method logic here }
3. Handle OPTIONS Requests in Global.asax
If you still see issues with preflight requests, explicitly handle OPTIONS requests in your Global.asax file to return the required headers immediately:
protected void Application_BeginRequest(object sender, EventArgs e) { if (Request.HttpMethod == "OPTIONS") { Response.StatusCode = 200; Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:XXXXX"); Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); Response.AddHeader("Access-Control-Allow-Headers", "Content-Type"); Response.End(); } }
Once you implement one of these server-side fixes, your Ajax call should work without the CORS block.
内容的提问来源于stack exchange,提问作者Chathilla. Vikram

