Blazor httpClient无法进行外部API调用



我想做一个简单的REST API调用,但似乎安全策略正在阻止我,我不知道如何修复它。代码调用一个开放的API来获取一个笑话。然而,我得到以下错误:dotnet.6.0.11.pbddgabtj1.js:1无法连接到"http://api.chucknorris"。因为它违反了文档的内容安全策略。

我已经在我的标题中添加了内容安全策略。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

执行调用的组件看起来像这样:

@page "/"
<PageTitle>Index</PageTitle>
<br />
<h4>Joke of the day:</h4>
<p>@joke</p>
@code{
string joke = "No Joke";
private readonly HttpClient clientHttp;
public Index()
{
clientHttp = new HttpClient();
}
protected override async Task OnInitializedAsync(){
var url = new Uri("http://api.chucknorris.io/jokes/random");
joke = "";
try
{
var result = await clientHttp.GetAsync(url);
joke = result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Failed to get the joke. Error: ", e.Message);            
}
if (string.IsNullOrEmpty(joke))
joke = "No Joke";
}
}

你知道我错过了什么吗?

找到答案了。您需要将API调用列入白名单。

<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
font-src 'self';
connect-src 'self' 
https://api.chucknorris.io/jokes/random;
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">

相关内容

  • 没有找到相关文章

最新更新