Med*_* W. 0 c# entity-framework .net-core asp.net-core blazor
我是 blazor 的新手,并尝试使用 .NET Core /EF Core 3 和 Visual Studio 2019 创建应用程序。我已经设置了一个数据库模型和一个 API,用于获取所有地址 (/api/Address) 并在浏览器中浏览到此返回数据库中的所有记录。但是我在 Razor 文件中的 My GetAsync 方法返回 401,最终返回 null。
这是我的剃刀代码:
@functions 
{
   Address[] addresses;
   protected override async Task OnInitializedAsync()
   {
     addresses = await Http.GetJsonAsync<Address[]>("api/Address");
   }
}
Run Code Online (Sandbox Code Playgroud)
这是我的 API
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class AddressController : ControllerBase
{
    private readonly MyDataContext _context;
    // GET: api/Address
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Address>>> GetAddresses()
    {
        return await _context.addressesDbSet.ToListAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)
我得到的所有错误说
 HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
Run Code Online (Sandbox Code Playgroud)
没有进一步说明,我无法理解原因,任何建议或建议将不胜感激。
我已经解决了这个问题,下面是我的解决方案,以防其他人遇到同样的问题。
注入后,HttpClient我HttpClient在调用之前将以下参数传递给GetAsSync:
var handler = new HttpClientHandler() 
{ 
    UseDefaultCredentials = false, 
    Credentials = System.Net.CredentialCache.DefaultCredentials,
    AllowAutoRedirect = true 
};
Http = new HttpClient(handler);
Http.BaseAddress = new Uri(/*YOUR BASE Uri*/);
Addresses = await Http.GetJsonAsync<Address[]>("api/Address");
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2064 次  |  
        
|   最近记录:  |