ASP.NET Blazor 添加 WebAPI 支持

ASP.NET Blazor 添加 WebAPI 支持

Program.cs

添加服务

1
builder.Services.AddControllers();

添加控制器

1
2
// add support for web api
app.MapControllers();

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

// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();

// add support for web api
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();

// add support for web api
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 可看到对应的输出


ASP.NET Blazor 添加 WebAPI 支持
https://taylorandtony.github.io/2025/01/26/blazor-add-api/
作者
TaylorAndTony
发布于
2025年1月26日
许可协议