AngularJS + ASP。NET Web API跨域问题。

时间:2021-08-24 12:19:39

Moving forward with my mobile app development learning process, I've found a new obstacle: Cross-origin Request Sharing or CORS.

继续我的移动应用开发学习过程,我发现了一个新的障碍:跨源请求共享或CORS。

I am using a combination of AngularJS + jQuery Mobile (Cordova phone client) and ASP.NET Web API (backend). My issue is that I have not been able to complete a POST request (or any other type of request) to an API controller.

我使用的是AngularJS + jQuery Mobile (Cordova手机客户端)和ASP。净Web API(后端)。我的问题是,我无法完成对API控制器的POST请求(或任何其他类型的请求)。

My AngularJS controller uses the $http.post() service method to call the Web API controller. However, Chrome debugger says that the call failed in an OPTIONS request (possibly the CORS preflight request).

我的AngularJS控制器使用$http.post()服务方法调用Web API控制器。但是,Chrome调试器说,在选项请求(可能是CORS飞行前请求)中调用失败。

I have implemented the CORS action selector from the following post: Enabling CORS in Web API Project. Even tough I can call the api method from Fiddler, AngularJS keeps failing on the OPTIONS preflight request.

我已经实现了下面文章中的CORS动作选择器:在Web API项目中启用CORS。即使很难调用Fiddler的api方法,AngularJS在飞行前的选项请求上仍然失败。

Is there anything I should be aware of about AngularJS and cross-domain calls? Any possible solution to my predicament?

关于AngularJS和跨域调用,有什么需要注意的吗?我的困境有什么可能的解决办法吗?

Thanks.

谢谢。

4 个解决方案

#1


10  

You can skip the preflight option request by using content-type : application/x-www-form-urlencoded.

您可以通过使用content-type: application/x-www-form- urlencodes来跳过飞行前选项请求。

AngularJS:

AngularJS:

var user = {
   ID: 1,
   Name: 'test'
};

$http({
  url: "api.localhost/api/users/addUser",
  method: "POST",
  data: $.param(user),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  withCredentials: true,
  }).success(function (data, status, headers, config) {
     console.log(data);
})

Web api:

Web api:

[HttpPost]
public string AddUser(User user)
{
    // Do something
    return user.Name + " added";
}

Web.config

. config

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
            <handlers>
                <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
                <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
                <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
                <remove name="OPTIONSVerbHandler" />
                <remove name="TRACEVerbHandler" />

                <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
                <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
                <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
            </handlers>
            <httpProtocol>
                <customHeaders>
                    <add name="Access-Control-Allow-Origin" value="http://localhost" />
                    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
                    <add name="Access-Control-Allow-Credentials" value="true" />
                    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                </customHeaders>
            </httpProtocol>
      </system.webServer>

#2


3  

While stumbling onto this issue with AngularJS 1.3 with Microsoft Web API 2 I found a simple solution to the CORS configuration issue.

当我在使用Microsoft Web API 2开发AngularJS 1.3时遇到这个问题时,我找到了一个解决CORS配置问题的简单解决方案。

  • First from Nuget intall - Microsoft WebApi Cors

    首先从Nuget intall -微软WebApi Cors

    Install-Package Microsoft.AspNet.WebApi.Cors
    
  • Then in your WebApiConfig.cs file:

    然后在你的WebApiConfig。cs文件:

    var cors = new System.Web.Http.Cors.EnableCorsAttribute("www.my-angular-web-site.com", "*", "*");
    
    config.EnableCors(cors);
    

You can also enable CORS everywhere with a * instead of your web site but that defeats the purpose of CORS and opens up security holes - but you can do it for testing.

您还可以在任何地方使用*而不是您的web站点启用CORS,但这违背了CORS的目的,并打开了安全漏洞——但是您可以在测试中使用它。

The WebApi.Cors assembly also lets you enable cors controller by controller or with other more granular details. Other details can be found here on the Web API site.

WebApi。Cors程序集还允许通过控制器或其他更细粒度的细节启用Cors控制器。其他细节可以在这个网站上找到。

#3


0  

Check out Thinktecture Cors objects, with those (nugettable) you can get full CORS support in WebApi without any code of your own.

查看Thinktecture Cors对象,有了这些对象,你可以在WebApi中得到完全的Cors支持,而不需要任何代码。

Even with a correct CORS implementation I've had a really strange issue with IIS 7 that was solved by enabling all verbs for WebDav (yes, WebDav - don't ask me why I just followed instructions on a blog post :-D).

即使使用正确的CORS实现,我也遇到了iis7的一个非常奇怪的问题,这个问题通过启用WebDav的所有谓词(是的,WebDav——不要问我为什么我只是遵循了博客文章中的指令:- d)得到了解决。

Do this:

这样做:

  • Open IIS manager, go to your application's Handler Mapping.
  • 打开IIS管理器,进入应用程序的处理程序映射。
  • Double click the WebDav handler
  • 双击WebDav处理程序
  • Click "Request Restriction"
  • 点击“请求限制”
  • On the "Verbs" tab, select "All verbs".
  • 在“动词”选项卡上,选择“所有动词”。

Again, no idea why WebApi uses WebDav, but this solved problems with POST and DELETE that wouldn't work in spite of a correct CORS implementation.

同样,不知道WebApi为什么使用WebDav,但这解决了POST和DELETE的问题,尽管有正确的CORS实现,但这不会起作用。

#4


-1  

Mostly the developers while running there UI and service on Localhost face this issue - There are many ways in which this can be resolved - alot of the developers tend to fix it at browser level " but thats a security breach.

大多数在本地主机上运行UI和服务的开发人员都面临这个问题——有很多方法可以解决这个问题——很多开发人员倾向于在浏览器级别修复它”但是这是一个安全漏洞。

Correct method is to fix this at your Web Service Layer- Following video will explain and solve this

正确的方法是在Web服务层解决这个问题——以下视频将解释并解决这个问题

Watch CORS- Implementing Cross Origin Resource Sharing ("EXPLAINED - Cross Origin Resource Sharing")!

观察CORS-实现跨源资源共享(“解释-跨源资源共享”)!

#1


10  

You can skip the preflight option request by using content-type : application/x-www-form-urlencoded.

您可以通过使用content-type: application/x-www-form- urlencodes来跳过飞行前选项请求。

AngularJS:

AngularJS:

var user = {
   ID: 1,
   Name: 'test'
};

$http({
  url: "api.localhost/api/users/addUser",
  method: "POST",
  data: $.param(user),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  withCredentials: true,
  }).success(function (data, status, headers, config) {
     console.log(data);
})

Web api:

Web api:

[HttpPost]
public string AddUser(User user)
{
    // Do something
    return user.Name + " added";
}

Web.config

. config

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
            <handlers>
                <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
                <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
                <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
                <remove name="OPTIONSVerbHandler" />
                <remove name="TRACEVerbHandler" />

                <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
                <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
                <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
            </handlers>
            <httpProtocol>
                <customHeaders>
                    <add name="Access-Control-Allow-Origin" value="http://localhost" />
                    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
                    <add name="Access-Control-Allow-Credentials" value="true" />
                    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                </customHeaders>
            </httpProtocol>
      </system.webServer>

#2


3  

While stumbling onto this issue with AngularJS 1.3 with Microsoft Web API 2 I found a simple solution to the CORS configuration issue.

当我在使用Microsoft Web API 2开发AngularJS 1.3时遇到这个问题时,我找到了一个解决CORS配置问题的简单解决方案。

  • First from Nuget intall - Microsoft WebApi Cors

    首先从Nuget intall -微软WebApi Cors

    Install-Package Microsoft.AspNet.WebApi.Cors
    
  • Then in your WebApiConfig.cs file:

    然后在你的WebApiConfig。cs文件:

    var cors = new System.Web.Http.Cors.EnableCorsAttribute("www.my-angular-web-site.com", "*", "*");
    
    config.EnableCors(cors);
    

You can also enable CORS everywhere with a * instead of your web site but that defeats the purpose of CORS and opens up security holes - but you can do it for testing.

您还可以在任何地方使用*而不是您的web站点启用CORS,但这违背了CORS的目的,并打开了安全漏洞——但是您可以在测试中使用它。

The WebApi.Cors assembly also lets you enable cors controller by controller or with other more granular details. Other details can be found here on the Web API site.

WebApi。Cors程序集还允许通过控制器或其他更细粒度的细节启用Cors控制器。其他细节可以在这个网站上找到。

#3


0  

Check out Thinktecture Cors objects, with those (nugettable) you can get full CORS support in WebApi without any code of your own.

查看Thinktecture Cors对象,有了这些对象,你可以在WebApi中得到完全的Cors支持,而不需要任何代码。

Even with a correct CORS implementation I've had a really strange issue with IIS 7 that was solved by enabling all verbs for WebDav (yes, WebDav - don't ask me why I just followed instructions on a blog post :-D).

即使使用正确的CORS实现,我也遇到了iis7的一个非常奇怪的问题,这个问题通过启用WebDav的所有谓词(是的,WebDav——不要问我为什么我只是遵循了博客文章中的指令:- d)得到了解决。

Do this:

这样做:

  • Open IIS manager, go to your application's Handler Mapping.
  • 打开IIS管理器,进入应用程序的处理程序映射。
  • Double click the WebDav handler
  • 双击WebDav处理程序
  • Click "Request Restriction"
  • 点击“请求限制”
  • On the "Verbs" tab, select "All verbs".
  • 在“动词”选项卡上,选择“所有动词”。

Again, no idea why WebApi uses WebDav, but this solved problems with POST and DELETE that wouldn't work in spite of a correct CORS implementation.

同样,不知道WebApi为什么使用WebDav,但这解决了POST和DELETE的问题,尽管有正确的CORS实现,但这不会起作用。

#4


-1  

Mostly the developers while running there UI and service on Localhost face this issue - There are many ways in which this can be resolved - alot of the developers tend to fix it at browser level " but thats a security breach.

大多数在本地主机上运行UI和服务的开发人员都面临这个问题——有很多方法可以解决这个问题——很多开发人员倾向于在浏览器级别修复它”但是这是一个安全漏洞。

Correct method is to fix this at your Web Service Layer- Following video will explain and solve this

正确的方法是在Web服务层解决这个问题——以下视频将解释并解决这个问题

Watch CORS- Implementing Cross Origin Resource Sharing ("EXPLAINED - Cross Origin Resource Sharing")!

观察CORS-实现跨源资源共享(“解释-跨源资源共享”)!