ASP.NET Core API:处理端点的 404 错误

问题描述 投票:0回答:1

我正在开发 ASP.NET Core API,并面临一个问题:尽管控制器和路由配置看似正确,但对 api 端点 (/api/plants/search) 的请求始终返回 404 错误。

尽管采用了如下所示的正确路由设置,为什么我的 API 端点可能始终返回 404 错误?任何人都可以识别所提供的代码中可能导致 /api/plants/search 端点出现 404 错误的任何错误配置吗?

  • 在我的开发环境中本地部署时,一切正常。所以,我猜控制器实际上设置正确。
  • 我已验证,我的 API 实际上已启动并正在运行,确实如此。它可以访问数据库。
  • 检查中间件的顺序以确保 UseCors、UseAuthentication、UseAuthorization 和端点路由配置正确。
  • 确保app.MapControllers();在Program.cs中调用。
  • 最初有 app.MapFallbackToController("Index", "Fallback");但将其注释掉以避免干扰 API 路由。
  • 检查了我的 IIS 配置并禁用了默认文档。

这是我的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);
    
    }
}

c# asp.net-core asp.net-mvc-routing
1个回答
0
投票

您错误地指定了方法的路线,它们应该以

/
:

开头
[HttpPost("/search")]
© www.soinside.com 2019 - 2024. All rights reserved.