【问题标题】:Cannot make CORS work - .NET 4.7.2. Receiving CORS Missig Allow Origin无法使 CORS 工作 - .NET 4.7.2。接收 CORS Missig 允许来源
【发布时间】:2021-10-14 21:26:42
【问题描述】:

有许多在线资源描述了如何在 .net Web 应用程序中配置 CORS。我什么都没做。

这是我的 API 应用程序的当前配置:

  • 安装了 nuget Microsoft.AspNet.WebApi.Cors

  • 更新了 WebApiConfig.cs:

    公共静态无效寄存器(HttpConfiguration 配置) {

         var cors = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
         config.EnableCors(cors);
         config.MapHttpAttributeRoutes();
    
         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{action}/{id}",
             defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
         );
     }
    

我认为以上内容足以使 CORS 为整个应用程序工作。它没。 我在 web.config 中添加了以下内容:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

这也不起作用。

我为每个控制器添加了 CORS 装饰器:

namespace ABC_API.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ABCController : ApiController

这也不起作用。

我正在尝试使用 Intuit 的 QuickBooks API,并在尝试获得授权时收到以下 CORS Missing Allow Origin 错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource 
at https://appcenter.intuit.com/connect/oauth2?client_id=ABkU7xzdcdsg1vSsKZ7NKZeypTST0EmnyvFhSNPMJM3NShYd5r&response_type
=code&scope=com.intuit.quickbooks.accounting&redirect_
uri=http%3A%2F%2Flocalhost%2FDW_QB_API%2Fapi%2Fauth&
state=e2543d40145e4eb30dbc4da099501d13aca48bc30b6529ad6af74acaae330581.
 (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

我错过了什么?

【问题讨论】:

标签: c# .net cors intuit


【解决方案1】:

在ConfigureServices 中配置应用程序启动时的 CORS 策略:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
}

对于每个请求:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    //app.UseMvc called last
    app.UseMvc();
}

或使用[EnableCors("MyPolicy")] 将策略应用于控制器和操作。

【讨论】:

  • 我有一个 global.asax.cs 文件而不是 startup.cs (.net 4.7.2)
猜你喜欢
  • 2021-04-28
  • 2019-10-27
  • 2017-04-27
  • 2013-11-28
  • 2021-05-13
  • 2021-11-11
  • 2020-12-29
  • 2022-07-26
  • 2017-05-13
相关资源
最近更新 更多