【问题标题】:How to resolve error 'Access to fetch at from origin has been blocked by CORS policy' in Blazor App如何解决 Blazor 应用程序中的错误“CORS 策略已阻止从源获取的访问”
【发布时间】:2021-09-08 22:53:11
【问题描述】:

我在互联网上搜索了很多关于 CORS 的信息,但我不明白我做错了什么。

我在浏览器控制台中遇到的错误是:

CORS 策略已阻止从源“https://localhost:44337”获取“https://localhost:44361/api/Contracts”的访问权限:否“Access-Control-Allow-Origin” ' 请求的资源上存在标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

GET https://localhost:44361/api/Contracts net::ERR_FAILED

我的 Blazor WebAssembly 应用程序中用于获取数据方法

public class ContractsUIRepository : IContractsUIRepository
{
    private readonly IHttpService _httpService;
    private readonly string url = "api/Contracts";
    public ContractsUIRepository(IHttpService httpService)
    {
        _httpService = httpService;
    }
    
    public async Task<List<ContractDTO>> GetAllContracts()
    {
        var response = await _httpService.Get<List<ContractDTO>>(url);
        if (!response.IsSucceed)
        {
            throw new ApplicationException(await response.GetBodyOfResponse());
        }
        return response.Response;
    }
}

我的HttpService.cs

public class HttpService : IHttpService
{
    private readonly HttpClient _httpClient;
    public HttpService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HttpResponseWrapper<T>> Get<T>(string url)
    {
        var httpResponseMessage = await _httpClient.GetAsync(url);
        if (httpResponseMessage.IsSuccessStatusCode)
        {
            var response = await Deserialize<T>(httpResponseMessage);
            return new HttpResponseWrapper<T>(true, response, httpResponseMessage);
        }
        else
        {
            return new HttpResponseWrapper<T>(false, default, httpResponseMessage);
        }
    }

    private static async Task<T> Deserialize<T>(HttpResponseMessage httpResponseMessage)
    {
        var responseString = await httpResponseMessage.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(responseString);
    }
}

HttpResponseWrapper.cs

public class HttpResponseWrapper<T>
{
    public bool IsSucceed { get; set; }
    public T Response { get; set; }
    public HttpResponseMessage HttpResponseMessage { get; set; }

    public HttpResponseWrapper(bool isSucceed, T response, HttpResponseMessage httpResponseMessage)
    {
        IsSucceed = isSucceed;
        Response = response;
        HttpResponseMessage = httpResponseMessage;
    }

    public async Task<string> GetBodyOfResponse()
    {
        return await HttpResponseMessage.Content.ReadAsStringAsync();
    }
}

我在Client项目中的Program.cs

public class Program
{
    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://localhost:44361/") });

        builder.Services.AddScoped<IHttpService, HttpService>();
        builder.Services.AddScoped<IContractsUIRepository, ContractsUIRepository>();

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

最后是 Server 项目中的 Startup.cs 文件:

public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "HAFProcurement.WebAPIs", Version = "v1" });
        });

        services.AddCors(options =>
        {
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins("https://localhost:44337/")
                      .AllowAnyHeader()
                      .AllowAnyMethod();
            });
        });
        
        services.AddSingleton<IDataAccess, OracleDataAccess>();
        services.AddSingleton<IContrRepository, ContrInMemory>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Procurement.WebAPIs v1"));
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseCors("default");
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

我是 C# 和 Blazor 的新手,我现在被卡住了。我需要你的帮助!

另外,我的 HttpService.cs 文件有问题吗?因为我不确定它是否正确..

提前谢谢你!

【问题讨论】:

  • 您可以尝试将 app.UseCors("default") 移动到 Configure 方法的开头,以便在管道中首先调用它并再次运行服务。
  • 我已经试过了。没用。还是谢谢!

标签: c# cors blazor


【解决方案1】:

尝试从 builder.WithOrigins 的 url 中删除反斜杠:

services.AddCors(options =>
{
    options.AddPolicy("default",
        builder =>
        {
            builder.WithOrigins("https://localhost:44337")
            .AllowAnyHeader()
            .AllowAnyMethod();
        });
});

使用https://localhost:44337 而不是https://localhost:44337/

【讨论】:

  • 你是对的!我完全忽略了它。非常感谢!
猜你喜欢
  • 2021-07-20
  • 2021-02-20
  • 2020-07-29
  • 2019-12-15
  • 2019-04-28
  • 1970-01-01
  • 2021-04-01
  • 2021-10-20
  • 2019-12-15
相关资源
最近更新 更多