.Net core 6 CORS问题

问题描述 投票:0回答:1

我有一个简单的 API,当我从另一个网站调用我的 API 时,出现 CORS 错误。我已经测试了所有内容,但似乎没有任何效果。该请求在 Postman 中运行良好。我有一个 API 密钥中间件,我也附上了它的代码。另一件事是,如果我在标头中传递 API 密钥,我只会收到 CORS 错误。如果我将它作为查询字符串传递,我不会收到任何错误,或者更准确地说,它会返回 404,但它会运行代码并返回结果:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using MY_API;
using MY_API.Data;
using MY_API.Middleware;


var builder = WebApplication.CreateBuilder(args);


// Add services to the container.

builder.Services.AddControllers().AddNewtonsoftJson();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<TestContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("Connection"));
});


builder.Services.AddCors(options =>
{
    options.AddPolicy("corsPolicy",
                      policy =>
                      {
                          policy
                               .AllowAnyOrigin()
                               .AllowAnyMethod()
                               .AllowAnyHeader();

                      });
});


var app = builder.Build();


if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("corsPolicy");
app.UseAuthentication();

app.UseAuthorization();


app.UseMiddleware<ApiKeyMiddleware>();

app.MapControllers();

app.Run();

我正在运行一个简单的 GET 请求。

// GET: api/Tests/5
[HttpGet("{id}")]
public async Task<ActionResult<Test>> GetTest(int id)
{
    var Test = await _context.Tests.FindAsync(id);

    if (Test == null)
    {
        return NotFound();
    }

    return Test;
}

我的API key中间件是这样的。请注意我用来在传递标头或查询字符串之间切换的注释行:

using System.Diagnostics;

namespace MY_API.Middleware
{
    public class ApiKeyMiddleware
    {
        private readonly RequestDelegate _next;
        private const string APIKEY = "apiKey";
        public ApiKeyMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
           if (!context.Request.Headers.TryGetValue(APIKEY, out var extractedApiKey))
             //   if (!context.Request.Query.TryGetValue(APIKEY, out var extractedApiKey))
                {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Api Key was not provided ");
                return;
            }

            var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();

            var apiKey = appSettings.GetValue<string>(APIKEY);

            if (!apiKey.Equals(extractedApiKey))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Unauthorized client");
                return;
            }


            await _next(context);
        }
    }
}

这是我得到的错误: Error

如果我将 API 作为查询字符串传递,我会得到类似这样的结果,但它会返回结果。请注意它是针对不同的 GET 请求并且名称不同:

Working one

asp.net-core cors http-get
1个回答
0
投票

我找到了问题的答案。 我必须在 IIS 管理器中允许选项:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.