调用 webapi 抛出请求的资源上不存在 Access-Control-Allow-Origin 标头 [英] Invoking webapi throws No Access-Control-Allow-Origin header is present on the requested resource

查看:13
本文介绍了调用 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 here https://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标签后,调用Ajax前需要先登录Web应用请求此 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.

如果您在登录前向 Web API 调用 Ajax 请求,由于 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 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆