如何从服务器端 Blazor Net Core 5.0 调用 API 控制器操作?

Ben*_*ior 13 asp.net-core asp.net-core-webapi blazor blazor-server-side

我创建了一个标准 Blazor 服务器应用程序。然后我添加了一个具有读/写操作的 API 控制器。

现在我想从索引页调用一个操作,但它不起作用。应用程序运行时没有错误,但没有返回预期的结果(状态=“等待激活”,方法=“null”和结果=“尚未计算”)。我在控制器操作中放置了一个断点,但程序从未命中它。

控制器:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET: api/<ValuesController>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)

索引页:

<button class="btn btn-primary" @onclick="RetrieveGet">
    GET
</button>

void RetrieveGet()
{
    HttpClient Http = new HttpClient();
    string baseUrl = "https://localhost:44382/";
    var temp2 = Task.Run(async () => { await Http.GetStringAsync($"{baseUrl}api/values/5"); });
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs(为简洁起见,删除了其他项目):

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 16

以下是您可以如何做到这一点。

1)创建一个新的 Blazor 服务器应用程序。

2)向应用程序的服务集合添加一些额外的配置。

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
            
    services.AddControllersWithViews();
    services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/"));
}
Run Code Online (Sandbox Code Playgroud)

上面代码的唯一区别是:

services.AddControllersWithViews();

// You should change the URI based on your project's needs.
// It's best to get the URI from appsettings.json.
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/"));
Run Code Online (Sandbox Code Playgroud)

3)配置应用程序的端点如下:

app.UseEndpoints(endpoints =>
{
    // This is the line you need to add
    endpoints.MapControllers();

    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");
});
Run Code Online (Sandbox Code Playgroud)

4)在 Blazor 页面中,您可以使用以下任一选项来访问 API:

  • 使用 HttpFactory。
  • 创建您自己的 HTTP 客户端。

选项 1:如果您决定使用 HttpFactory,您应该在页面顶部添加以下代码: @inject IHttpClientFactory ClientFactory

在你的函数内部按如下方式使用它:

var clientlocal = ClientFactory.CreateClient("LocalApi");
var res = await clientlocal.GetStringAsync("api/values/5");
Run Code Online (Sandbox Code Playgroud)

当然,您还需要更改您的函数签名: async Task RetrieveGet()

选项 2:如果您选择创建自己的 HTTP 客户端,则需要按如下方式调用 API:

HttpClient Http = new HttpClient();
string baseUrl = "https://localhost:44333/";
var temp2 = await Http.GetStringAsync($"{baseUrl}api/values/5");
Run Code Online (Sandbox Code Playgroud)

当然,您需要更改您的函数签名: async Task RetrieveGet()

以下是这两种方法的屏幕截图。请注意相同的 URL: 相同的网址

正如预期的那样,应用程序现在到达了断点: 调用控制器

这是返回结果: 返回结果

你有它。如果您有任何疑问,请告诉我。