首页 > 解决方案 > Blazor webassembly 独立客户端的 Cors 问题

问题描述

我正在为 DELETE 和 POST 解决一些 cors 问题。

GET 工作正常。

设置是:Azure API 管理中的 .Net 核心 API 和调用 API 的 Blazor webassembly 独立客户端(Azure 应用服务)。

尝试删除时出现的错误是。

“已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:不存在‘Access-Control-Allow-Origin’标头”

所以我发现很难理解这里需要什么代码。.net 核心的 CORS 以及不同的 Blazor 设置(服务器、托管 wasm 等)到处都是如此多的示例。

我想我需要以某种方式处理预检请求才能使其正常工作?

这是我现在使用的:

我调用 API 的 ServiceTimes.razor

@code {

private const string ServiceEndpoint = "https://MyProdAPI.azure-api.net/api/ServiceTimes";
private LWS_ServiceTimes[] servicetimes;



LWS_ServiceTimes servicetimeObj = new LWS_ServiceTimes();

string ids = "0";
bool showAddrow = false;

bool loadFailed;

protected override async Task OnInitializedAsync()
{
    ids = "0";
    try
    {
        servicetimes = await Http.GetFromJsonAsync<LWS_ServiceTimes[]>(ServiceEndpoint);
    }
    catch (AccessTokenNotAvailableException exception)
    {
        exception.Redirect();
    }
}


// Delete Method
protected async Task DeleteServiceTimes(long ServiceTimesID)
{
    showAddrow = false;

    ids = ServiceTimesID.ToString();
    await Http.DeleteAsync("https://MyprodAPI.azure-api.net/api/ServiceTimes/1"); //Deletes the ID=1

 }

Blazor webassembly 独立客户端 Program.cs

 public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");

        builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://prodsite.azurewebsites.net") });

        builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.DefaultAccessTokenScopes.Add("api://xxxxxxxx-xxxx-xxxx-xxxx-xxxx/API.Access"); //API.Acess my scope in API
        });

        builder.Services.AddHttpClient("ServerAPI",
    client => client.BaseAddress = new Uri("https://MyprodAPI.azure-api.net"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

        builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
            .CreateClient("ServerAPI"));

        await builder.Build().RunAsync();
    }

API 启动

public void ConfigureServices(IServiceCollection services)
    {
        
        services.AddDbContext<LwsSpiderContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));

        services.AddSwaggerGen();

      

         services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("https://prodsite.azurewebsites.net");
                                 builder.AllowAnyMethod();
                                builder.WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization, "x-custom-header");
                                  builder.AllowCredentials();
        });
        });
        services.AddControllers();
        
      }

   
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseSwagger();

       // app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("MyAllowSpecificOrigins");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
    }

标签: blazor-client-side

解决方案


推荐阅读