我正在开发 ASP.NET Core API,并面临一个问题:尽管控制器和路由配置看似正确,但对 api 端点 (/api/plants/search) 的请求始终返回 404 错误。
尽管采用了如下所示的正确路由设置,为什么我的 API 端点可能始终返回 404 错误?任何人都可以识别所提供的代码中可能导致 /api/plants/search 端点出现 404 错误的任何错误配置吗?
这是我的Program.cs的代码:
using API;
using API.Data;
using API.Extensions;
using API.Middleware;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddApplicationServices(builder.Configuration);
builder.Services.AddIdentityServices(builder.Configuration);
builder.Logging.AddConsole();
var connString = "";
connString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataContext>(opt =>
{
opt.UseSqlServer(connString);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseMiddleware<ExceptionMiddleware>();
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
// app.UseDefaultFiles();
// app.UseStaticFiles();
app.MapControllers();
// app.MapFallbackToController("Index", "Fallback");
using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DataContext>();
await context.Database.MigrateAsync();
await Seed.SeedAdmin(context);
}
catch (Exception ex)
{
var logger = services.GetService<ILogger<Program>>();
logger.LogError(ex, "An error occurred during migration");
}
app.Run();
这是我的 appsettings.json 的内容(出于安全原因,我删除了连接字符串和令牌密钥):
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "CONNECTION STRING"
},
"TokenKey": "TOKEN KEY"
}
我的ApplicationServiceExtensions.cs的内容:
using API.Data;
using API.Interfaces;
using API.Services;
namespace API.Extensions
{
public static class ApplicationServiceExtensions
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services,
IConfiguration config)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins(
"https://localhost:4200",
"https://plantguide.ch",
"https://www.plantguide.ch",
"https://edgarsplantguide.com",
"https://www.edgarsplantguide.com"
)
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<IPlantRepository, PlantRepository>();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
return services;
}
}
}
我的BaseApiController.cs的内容:
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class BaseApiController: ControllerBase
{
}
}
我的 PlantsController.cs 的内容:
using API.Data;
using API.Entities;
using API.Interfaces;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace API.Controllers;
public class PlantsController: BaseApiController
{
private readonly IPlantRepository _plantRepository;
private readonly IMapper _mapper;
// Plant controller constructor
public PlantsController(IPlantRepository plantRepository, IMapper mapper)
{
_mapper = mapper;
_plantRepository = plantRepository;
}
[HttpPost("search")] // /api/plants/search
public async Task<ActionResult<IEnumerable<Plant>>> SearchPlants([FromBody] PlantSearchFormDto searchDto)
{
var results = await _plantRepository.GetPlantsBasedOnSearchFormContentAsync(searchDto);
return Ok(results);
}
[HttpGet("{id}")] // /api/plants/1
public async Task<ActionResult<Plant>> GetPlantByIdAsync(int id)
{
return await _plantRepository.GetPlantByIdAsync(id);
}
}
您错误地指定了方法的路线,它们应该以
/
: 开头
[HttpPost("/search")]