【问题标题】:Enable cors in wcf - ajax在 wcf 中启用 cors - ajax
【发布时间】:2026-01-07 02:45:02
【问题描述】:

我是 WCF 的初学者,我一直在尝试为我的 IIS 中托管的 WCF 服务启用 CORS。我浏览了几篇帖子和 Stack Overflow 问题,所有答案都引导我找到不同的解决方案,但没有一个有效。

谁能解释我如何实现这一点?我尝试创建一个 global.asax 并添加 begin_request 事件来设置标题,但它没有任何改变。 这是我用的:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

我应该从哪里开始?实现这一目标的最佳方式是什么?

【问题讨论】:

  • 你试过这个enable-cors.org/server_wcf.html 吗?
  • @MajoB 是的,但我无法正确配置它,它给了我很多例外
  • 您是否已将Access-Control-Allow-Origin 添加到网络配置中
  • 那些例外是什么?

标签: c# wcf iis cors


【解决方案1】:

我假设 WCF 服务已启动并正在运行。在 Web.config 中修复。在 system.webServer 部分中添加以下部分。

<httpProtocol>
<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>

注意


注意! Access-Control-Allow-Origin 设置设置为值"*"。这将允许所有调用者访问。您只能指定您的来电者。

从您现有的实现来看,它应该可以工作。但是我稍微调整了代码,它对我有用。

protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
{    
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Origin, Content-Type, Accept, X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}

【讨论】: