Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

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

I created a standard Blazor server app then I added an API Controller with read/write actions Now I want to call the action from the index page but it doesn't work. It runs without error but doesn't return the expected (status = "Waiting for activation", Method = "null" and result = "Not yet computed"). I put a breakpoint in the controller action but it doesn't reach there.

// 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");
            });
        }
question from:https://stackoverflow.com/questions/65929120/how-to-call-api-controller-action-from-server-side-blazor-net-core-5-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer you can !! here is how to do it

1- created new Blazor server app

2- Edit configure service

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

the only diff here is

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- Edit Configure as following

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

4- In your Blazor page you could use one of the following options

  • Use Httpfactory

  • Create your own http client

If you decided to use htppFactory you should add the following code in the top of your page

@inject IHttpClientFactory ClientFactory

And inside your function use it as follwoing

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

of course you need to change your function signature

async Task RetrieveGet()

the other option which is creating your own client you need to call your api as following

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

of course you need to change your function signature

async Task RetrieveGet()

Here is screenshot for either way Notice the same URL

Already calling the controller

and here is the return result enter image description here

Here you have it Let me know if you have any questions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...