本文介绍了调用webapi引发请求的资源上不存在Access-Control-Allow-Origin标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Azure示例通过此处提供的WSFederation将Azure AD集成到我的MVC 4.6 Web应用程序中 https://github.com/Azure-Samples/active-directory- dotnet-webapp-wsfederation

I'm trying to follow an Azure sample to integrate Azure AD into my MVC 4.6 web app via WSFederation provided herehttps://github.com/Azure-Samples/active-directory-dotnet-webapp-wsfederation

此示例按预期方式工作.但是,当我在同一MVC项目中添加WebApi控制器并用[Authorize]装饰时,会出错.我在这个新添加的WebApi控制器中对GET方法提出了ajax请求.

This sample works as expected. However, when I add a WebApi controller in the same MVC project and decorate with [Authorize] it errors out. I have an ajax request for GET method in this newly added WebApi controller.

错误是:

XMLHttpRequest cannot load https://login.microsoftonline.com/85c96496-fbc6-4bf3-bfcc-fb51ca874527/wsfe…UIWNgv-EANzWADAQPCOqF--3c7KGt6G21ucvLkce_wMcwVguKz62ioyGPxQg&wa=wsignin1.0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:4279' is therefore not allowed access.

感谢您的帮助!

推荐答案

为Web API添加Authorize标记后,需要先登录Web应用程序,然后才能调用Ajax请求此Web API.然后,Ajax请求将自动发送cookie以进行身份​​验证,并将返回正确的结果.

After you add the Authorize tag for the web API, you need to sign-in the web app before you call the Ajax to request this web API. Then the Ajax request will send the cookies automatically for the authentication and it would return the correct result.

如果在登录之前调用Ajax请求到Web API,由于Web API受保护并且Web应用程序正在与Azure AD集成,因此该请求将重定向到Azure AD的登录页面跨域请求.这是此问题的根本原因.

If you call the Ajax request to the web API before you sign-in, since the web API is protected and the web app is integrating with Azure AD, the request would redirect to the login page of Azure AD which is not allowed cross domain request. That's the root reason for this issue.

这篇关于调用webapi引发请求的资源上不存在Access-Control-Allow-Origin标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:04