【问题标题】:How to call Api controller action from server side blazor Net Core 5.0?如何从服务器端 blazor Net Core 5.0 调用 Api 控制器操作?
【发布时间】:2021-05-01 21:02:00
【问题描述】:

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

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

【问题讨论】:

标签: asp.net-core asp.net-core-webapi blazor blazor-server-side


【解决方案1】:

你可以简答!! 这是怎么做的

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()

这是两种方式的屏幕截图

这是返回结果

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

【讨论】:

  • 效果很好。在生产环境中,将 api 移动到 NetCoreWebApi 可能更有意义,但对于开发和测试,我认为仅在一个项目中执行此操作更实用。
  • 我很高兴它对你有用!!同意,但这取决于您的业务需求,tbh 开发结构应该与生产结构相同,否则您会感到惊讶:) 只有差异应该是配置
  • 授权如何在这种方法中工作。当api有Authorize属性时我们应该怎么做?
  • @Cododoc 您需要将 Authorization 标头添加到您的 httpclinet 并添加 Bearer JWTToken (这应该是您的访问令牌)类似于 {your httpClient}.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer ", "JWTToken");
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 2020-07-30
  • 2019-02-20
  • 2022-01-14
  • 2019-10-06
  • 2020-09-30
  • 1970-01-01
相关资源
最近更新 更多