受欢迎的博客标签

Blazor server app with CRUD operations call a Web API Controller(not view)

Published

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

How to add controller (not view) support to a server-side Blazor project?

.Net 5.x

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

1- created new Blazor server app
2- created new API Controller
3- Edit Configure add  endpoints.MapControllers(); 

2- created new API Controller

path:F:\src\BlazorServer\Stockso.BlazorServer\Controllers\CommonController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Stockso.BlazorServer.Controllers
{


    [Route("api/[controller]")]
    [ApiController]
    public class CommonController : ControllerBase
    {

        /// 收盘后安装数据到mongodb数据库
        /// http://localhost:5000/api/Common/KeepAlive
        /// </summary>
        /// <returns></returns>
        [HttpGet("KeepAlive")]
        public async Task<IActionResult> KeepAlive()
        {
            
            return Ok("I am alive!");
        }
    }
}

test

http://localhost:5000/api/Common/KeepAlive
Output
Sorry
Sorry, there's nothing at this address.

3- Edit Configure as following

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

Test

http://localhost:5000/api/Common/KeepAlive

Output
I am alive!

Useful links

https://stackoverflow.com/questions/65929120/how-to-call-api-controller-action-from-server-side-blazor-net-core-5-0

https://stackoverflow.com/questions/60022519/how-to-add-controller-not-view-support-to-a-server-side-blazor-project

http://blog.medhat.ca/2019/06/blazor-server-side-app-with-crud.html

 

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio