Reputation: 223
In my ASP.NET Core hosted Blazor web assembly, I have a controller as shown here in the server project:
[ApiController]
[Route("api/[controller]")]
public class BlogController : ControllerBase
{
private readonly AppDbContext _context;
public BlogController(AppDbContext context)
{
_context = context;
}
[HttpGet("GetPagedBlogs")]
public async Task<ActionResult<List<Blog>>> GetPagedBlogs()
{
var blogs = _context.Blogs.OrderByDescending(x => x.Created).ToList();
return Ok(blogs ;
}
}
When I try to send a request to
https://mydomain/api/blog/GetPagedBlogs
it doesn't reach this action method. But if I replace [HttpGet("GetPagedBlogs")]
with just [HttpGet]
and send request to https://mydomain/api/blog
, then it reaches the action method.
What am I missing?
I am using .NET 7 and here is my program.cs
file
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
Upvotes: 1
Views: 419
Reputation: 755073
In order to enable the attribute-based routing in ASP.NET Core Web API, you need to replace:
builder.Services.AddControllersWithViews();
(this is for ASP.NET Core MVC - where you have controllers with views)
with
builder.Services.AddControllers();
to enable Web API controllers with attribute-based routing.
Upvotes: 0