在 Azure Web 应用程序中为 Web API 启用 CORS

Enabling CORS for Web API in Azure Web Apps

我已经将 Web API 项目部署到 Azure Web 应用程序。从 angularjs 应用程序,我正在尝试向 API 发出 $http.get 请求。但是它给出了一个 CORS(跨源)异常,尽管我已经在我的 Web API 启动配置

中启用了它
 app.UseCors(CorsOptions.AllowAll);

我想为 Azure Web 应用程序启用 CORS,我相信这会解决问题

编辑 http://nearestbuyweb.azurewebsites.net/ this is the URL of the Web app. It is trying to access http://nearestbuyapi.azurewebsites.net/api/MenuBar发生异常的地方。

我认为使用 Azure Web App 是不可能的。 MSDN Question

请帮忙!

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <clear />
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

您需要使用 web.config 删除 IIS 中的选项处理程序。 http://eugeneagafonov.com/post/38312919044/iis-options-cors-aspnet-webapi-en

我在 Azure 中使用 CORS 使用它:

WebApiConfig.cs:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "PublicApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

Web.config:

  <system.webServer>
  <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 设置让 其他 网站访问您网站的 API。不访问其他站点的 APIs.

根据您的意见,当您尝试从您的站点发出外部请求时,您似乎遇到了 CORS 错误。这正是 CORS 应该阻止的行为。

要消除错误,您必须在 API 您尝试访问的站点上应用 CORS 配置设置

在您的情况下,您要确保在 http://nearestbuyapi.azurewebsites.net site. NOT on http://nearestbuyweb.azurewebsites.net/

上应用配置更改

抱歉各位,

该问题仅发生在我的公司网络中。谷歌搜索后我发现公司网络可以禁用 CORS 请求。在这里找到这个 link