ASP.NET Blazor 添加 WebAPI 支持
Program.cs
添加服务
1
| builder.Services.AddControllers();
|
添加控制器
Program.cs 完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| using BlazorApiTest.Components;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents() .AddInteractiveServerComponents();
builder.Services.AddControllers();
var app = builder.Build();
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); }
app.UseStaticFiles(); app.UseAntiforgery();
app.MapRazorComponents<App>() .AddInteractiveServerRenderMode();
app.MapControllers();
app.Run();
|
编写控制器
创建 Controllers/BasicController.cs
名称任意
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| using Microsoft.AspNetCore.Mvc;
namespace BlazorApiTest.Controllers;
[Route("api/")] [ApiController] public class BasicController: Controller { [HttpGet("test")] public string Get() { return "Hello, World!"; } }
|
启动程序访问 /api/test
即可看到正确回显 Hello, World!
或者,使用约定的路由方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| using Microsoft.AspNetCore.Mvc;
namespace BlazorApiTest.Controllers;
[Route("api/[controller]/[action]")] [ApiController] public class BasicController: Controller { public string Hello() { return "Hello, World! From Hello() method"; }
public string Goodbye() { return "Goodbye, World! From Goodbye() method"; } }
|
此时,访问 /api/Basic/Hello
和 /api/Basic/Goodbye
可看到对应的输出