我正在自学 Blazor,遇到了这个难题,出现以下错误:
{“无法建立连接,因为目标机器主动拒绝。”}
我调用的 uri 是这个:
api/员工
但是,当使用完整的 uri 时,如下所示:
https://localhost:44376/api/employee
我完全没有收到任何错误。
尽管这只是一个练习项目,我仍然更喜欢使用不带端口号的相对 uri,但不确定如何使其工作。
这是我进行这些调用的方法:
public async Task<IEnumerable<Employee>> GetAllEmployees()
{
bool isEmployeeListEmpty = true; ;
IEnumerable<Employee> employeeList = null;
try
{
//string uriEmployeeList = $"https://localhost:44376/api/employee";
string uriEmployeeList = $"api/employee";
var employees = await JsonSerializer.DeserializeAsync<IEnumerable<Employee>>
(await _httpClient.GetStreamAsync(uriEmployeeList), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
if (employees != null)
{
isEmployeeListEmpty = false;
employeeList = await JsonSerializer.DeserializeAsync<IEnumerable<Employee>>
(await _httpClient.GetStreamAsync(uriEmployeeList), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
else
{
isEmployeeListEmpty = true;
}
}
catch (Exception ex)
{
Console.WriteLine("An exception occurred inside the GetAllEmployees() method of the EmployeeDataService class");
Console.WriteLine(ex.Message);
}
if (!isEmployeeListEmpty)
return employeeList;
else
return null;
}
我使用 IIS Express 在一台计算机上完成这一切。
更新
感谢大家的帮助和建议。事实证明,我在 lauchSettings.json
中将 ssl 端口定义为 44376
,而我在 Startup.cs
文件中定义了基地址对于我使用的所有三个 HttpClient 对象,设置为 https://localhost:44340/
。我将每个基地址中的端口更改为 44376
,以匹配我在 launchSettings.json
文件中设置的 44376
端口,并且现在一切都可以使用相对/缩写 uri 字符串。
最佳答案
请检查api和web项目是否在“多次启动”下设置,并且都是ACTION:“启动”不是(右键单击“解决方案”>“设置启动项目”),似乎api项目未启动并拒绝连接并在访问 api Controller 时出现类似的错误。
关于asp.net-core - Blazor 项目中出现 "No connection could be made because the target machine actively refused it."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73148072/