Blazor WebAssembly调用WebService出现CORS跨域请求阻塞问题求助
问题描述
直接访问https://zenquotes.io/api/random能获取励志语录,但在Visual Studio 2022默认的Blazor WebAssembly App模板项目中,修改SurveyPrompt.razor调用该接口时出现CORS错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...
修改后的SurveyPrompt.razor代码如下:
@inject HttpClient http <div class="alert alert-secondary mt-4"> <p> <span class="oi oi-pencil me-2" aria-hidden="true"></span> <strong>@Title</strong></p> @if (HTML is not null) { @((MarkupString)HTML) } </div> @code { // Demonstrates how a parent component can supply parameters [Parameter] public string? Title { get; set; } private string? HTML { get; set; } protected override async Task OnInitializedAsync() { await GetQuote(); } private async Task GetQuote() { try { string url = "https://zenquotes.io/api/random"; var response = await http.GetFromJsonAsync<QuoteResponse>(url); HTML = response is not null ? response[0]?.h ?? string.Empty : string.Empty; } catch (Exception e) { HTML = e.Message; } } class QuoteResponse { public string? q { get; set; }//quote public string? a { get; set; }//author public string? i { get; set; }//author image public int? c { get; set; }//char count public string? h { get; set; }//html } }
原因分析
- 浏览器地址栏直接访问属于简单GET请求,不属于AJAX跨域范畴,不会触发浏览器的CORS预检查机制,因此能正常获取内容。
- Blazor WebAssembly应用内的调用属于前端AJAX跨域请求:当请求的域名、协议、端口任意一项和当前应用的源不一致时,浏览器会要求目标服务器返回允许跨域的响应头(如
Access-Control-Allow-Origin)。但zenquotes.io的服务器未配置允许你的Blazor应用域名跨域访问,所以浏览器拦截了响应,抛出CORS错误。
解决方法
方法1:配置后端API代理(推荐,适用于生产环境)
如果你的Blazor WebAssembly是托管在ASP.NET Core后端的项目,可在后端配置反向代理,让后端转发请求规避跨域问题:
- 在后端项目的
Program.cs中添加代理服务:
using Microsoft.AspNetCore.WebUtilities; var builder = WebApplication.CreateBuilder(args); // 添加反向代理服务 builder.Services.AddReverseProxy() .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); var app = builder.Build(); // 启用代理路由 app.MapReverseProxy(); // 其他中间件配置... app.Run();
- 在后端的
appsettings.json中添加代理规则:
{ "ReverseProxy": { "Routes": { "zenquotes": { "ClusterId": "zenquotes", "Match": { "Path": "/api/zenquotes/{**catch-all}" }, "Transforms": [ { "PathRemovePrefix": "/api/zenquotes" } ] } }, "Clusters": { "zenquotes": { "Destinations": { "zenquotes": { "Address": "https://zenquotes.io/api/" } } } } } }
- 修改Blazor组件中的请求地址为后端代理地址:
string url = "/api/zenquotes/random";
方法2:使用CORS代理服务(仅临时测试用)
可以用公开的CORS代理服务包装请求,但生产环境不建议使用,存在安全风险。修改组件中的请求地址:
string url = "https://cors-anywhere.herokuapp.com/https://zenquotes.io/api/random";
方法3:请求API提供商配置跨域规则
如果有权限,可联系zenquotes.io的管理员,请求将你的Blazor应用域名添加到他们的CORS允许列表中,配置Access-Control-Allow-Origin响应头允许跨域访问。
内容的提问来源于stack exchange,提问作者blaze_125
相关产品推荐
相关产品推荐

