Jan*_*ane 7 .net inject blazor-server-side
当我尝试注入 HttpClient 时,我在 razor 页面中收到错误:
未处理的承诺拒绝:错误:System.InvalidOperationException:无法为类型上的属性“Http”提供值。没有“System.Net.Http.HttpClient”类型的注册服务。
请审查并提供反馈。
在Razor Component它不需要@inject
请参阅下面的示例:
<div class="row">
<div class="col-4">
<label for="cities">Choose city</label>
<input type="text" class="form-control" id="citiy" @bind="@cityName" />
</div>
<div class="col-3">
<button class="btn btn-primary" @onclick=@GetWeather>Get weather for @cityName</button>
</div>
</div>
<div class="row">
<div class="col-8 offset-2">
<pre id="json"><code>@ResultStr</code></pre>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
还有那@code部分
@code {
string cityName = "";
string ResultStr= "...";
string reqUrl => $"http://api.openweathermap.org/data/2.5/weather?q={cityName}&APPID=appID";
async Task GetWeather()
{
try
{
HttpClient client = new HttpClient();
ResultStr= "...";
var response = await client.GetAsync(reqUrl);
if (response.IsSuccessStatusCode)
ResultStr= await response.Content.ReadAsStringAsync();
else
ResultStr= response.ReasonPhrase;
}
catch (Exception ex)
{
ResultStr= ex.ToString();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这对我有用..=)
| 归档时间: |
|
| 查看次数: |
5549 次 |
| 最近记录: |