我想做什么
我有一个Azure免费计划托管的后端ASP.Net核心Web API(源代码:https://github.com/killerrin/Portfolio-Backend).
我还有一个客户网站,我想要消费该API.客户端应用程序不会托管在Azure上,而是托管在Github Pages或我可以访问的其他Web托管服务上.因此,域名不会排队.
考虑到这一点,我需要在Web API端启用CORS,但是我现在已经尝试了好几个小时并拒绝工作.
我如何设置客户端 它只是一个用React.js编写的简单客户端.我在Jquery中通过AJAX调用API.React网站有效,所以我知道不是这样.Jquery API调用正如我在Attempt 1中确认的那样工作.这是我如何进行调用
var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
//alert(username + "|" + password + "|" + apiUrl);
$.ajax({
url: apiUrl,
type: "POST",
data: {
username: username,
password: password
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var authenticatedUser = JSON.parse(response);
//alert("Data Loaded: " + authenticatedUser);
if (onComplete != null) {
onComplete(authenticatedUser);
}
},
error: function (xhr, status, error) {
//alert(xhr.responseText);
if (onComplete != null) {
onComplete(xhr.responseText);
} …Run Code Online (Sandbox Code Playgroud) 我的IDE是Visual Studio 2017.我有一个Angular4客户端与Core中的WebAPI后端通信,而CORS正在为PUT和POST方法配置EXCEPT.GET方法在Chrome中使用与PUT和POST方法相同的预检OPTIONS方法,但GET工作正常.
Visual Studio中的IIS Express服务器似乎没有将请求转发到Kestrel服务器.两种方法都适用于Postman,但是当Angular4进行调用时则不行.这是代码:
Angular4 POST
post(api: string, object: any): Observable<any> {
let body = JSON.stringify(object);
let options = new RequestOptions({
headers: this.headers,
withCredentials: true
});
return this.http.post(this.server + api, body, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error) || 'Post server error');
}
Run Code Online (Sandbox Code Playgroud)
Startup.cs配置
services.Configure<IISOptions>(options =>
options.ForwardWindowsAuthentication = true);
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => {
builder.WithOrigins("http://localhost:XXXX")
.WithMethods("GE??T", "POST", "PUT", "DELETE", "OPTIONS")
.WithHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
.AllowCredentials();
});
});
Run Code Online (Sandbox Code Playgroud)
Startup.cs ConfigureServices
app.UseCors("AllowAll");
Run Code Online (Sandbox Code Playgroud)
Project中的IIS ApplicationHost.Config
<anonymousAuthentication …Run Code Online (Sandbox Code Playgroud) 我在预检请求方面遇到了一个奇怪的问题。
这是在我们的应用程序中执行某些操作后,它在 Chrome(以及其他基于 chromium 的浏览器)中的外观:

许多预检请求被标记为红色失败 (net::ERR_FAILED)。
但最终,每个请求都会有一个预检请求,该请求成功并返回204,并且应用程序可以正常工作。所以看起来浏览器尝试了几次,最终没问题,但是日志中的许多项目都是红色的......
在 Firefox 中,预检请求甚至不可见,看起来一切都很好:

在 API 的 Program.cs 中,我们有这样的代码,它应该使它始终可以使用 AllowAnyMethod() 工作,它应该接受任何 OPTIONS 请求:
var allowedOrigins = app.Configuration.GetSection("appSettings") != null
? app.Configuration.GetSection("appSettings").GetSection("AllowedCorsOrigins").GetChildren().Select(x => x.Value).ToArray()
: Array.Empty<string>();
Trace.WriteLine("allowed origins:" + string.Join(',', allowedOrigins));
app.UseCors(x => x
.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithExposedHeaders("Content-Disposition"));
Run Code Online (Sandbox Code Playgroud)
我还尝试使用中间件来解决这个问题:/sf/answers/2953983091/ 但它的工作原理是一样的。
Chrome 发出如此多失败的预检请求的原因可能是什么?正常吗?是 Chrome 错误、网络错误还是 API 错误?
谢谢您的回答。我可以添加更多信息,只需告诉我您需要了解的内容即可。
顺便说一句,我在控制台日志中没有任何 CORS 错误。
我正在尝试从 angular 应用程序连接到我的 .net 核心 API。当我尝试这样做时,我收到一条错误消息:
Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
下面是来自我的 angular 应用程序的控制台消息:
这是我为解决错误所做的工作。我在 startup.cs 文件的 ConfigureServices 方法中添加了 services.addCors :
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddDbContext<db_recloadContext>();
}
Run Code Online (Sandbox Code Playgroud)
在configure方法中,我放了以下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyCorsPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{ …Run Code Online (Sandbox Code Playgroud)