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

How to call Api controller action from server side blazor Net Core 5.0?

我创建了一个标准的 Blazor 服务器应用程序,然后我添加了一个具有 read/write 操作的 API 控制器 现在我想从索引页面调用操作,但它不起作用。它运行没有错误,但没有 return 预期(状态 =“等待激活”,方法 =“空”和结果 =“尚未计算”)。 我在控制器操作中放置了一个断点,但它没有到达那里。

// ValuesController
       [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";
            }

// Index page
    <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"); });
    }


// Startup.cs  (other items removed for brevity)
  
        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");
            });
        }

简答可以!! 这是如何做到的

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/"));
    }

这里唯一的不同是

services.AddControllersWithViews();
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/")); // you could change this based on your project the right way is to get it from appsettings.json

3- 编辑配置如下

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers(); //<======= this is the line you need to add 
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });

4- 在您的 Blazor 页面中,您可以使用以下选项之一

  • 使用 Httpfactory

  • 创建您自己的 http 客户端

如果您决定使用 htppFactory,您应该在页面顶部添加以下代码

@inject IHttpClientFactory ClientFactory

并在您的函数中将其用作以下内容

var clientlocal = ClientFactory.CreateClient("LocalApi");
var res = await clientlocal.GetStringAsync("api/values/5");

当然你需要改变你的函数签名

async Task RetrieveGet()

另一种选择是创建您自己的客户端 您需要按以下方式调用 api

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

当然你需要改变你的函数签名

async Task RetrieveGet()

这是两种方式的屏幕截图

这是 return 结果

给你 如果您有任何问题,请告诉我