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
http://blog.medhat.ca/2019/06/blazor-server-side-app-with-crud.html