You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6属性路由返回404:FilesController多GET接口无法访问

解决FilesController多GET接口404问题

问题分析

你的FilesController两个GET接口返回404,核心原因是路由模板存在模糊匹配:

  • /api/files/{id} 模板会匹配任何/api/files/xxx格式的请求,包括/api/files/DownloadFile/test.csv(此时DownloadFile会被当作id参数)
  • 路由系统优先匹配更通用的模板,导致第二个DownloadFile接口永远无法被命中,最终返回404

解决方案

1. 给参数添加类型约束(推荐)

给{id}参数添加类型约束,让路由系统能明确区分两个接口的匹配规则:

[Route("api/[controller]")]
[ApiController]
public class FilesController : ControllerBase
{
    // 仅匹配数字类型的id
    [HttpGet("{id:int}")]
    public IActionResult GetFileById(int id)
    {
        // 你的业务逻辑
        return Ok();
    }

    [HttpGet("DownloadFile/{fileName}")]
    public IActionResult DownloadFile(string fileName)
    {
        // 你的下载逻辑
        return File(...);
    }
}

如果id是字符串类型,可以给DownloadFile路由添加更明确的前缀,或者使用路由约束排除特定值:

// 排除id等于"DownloadFile"的情况
[HttpGet("{id:regex(^(?!DownloadFile$).*)}")]
public IActionResult GetFileById(string id)
{
    // 逻辑代码
}

2. 调整路由模板的明确性

将两个接口的路由模板设置为完全不重叠的格式:

[Route("api/[controller]")]
[ApiController]
public class FilesController : ControllerBase
{
    // 明确指定路由前缀
    [HttpGet("ById/{id}")]
    public IActionResult GetFileById(string id)
    {
        // 逻辑代码
    }

    [HttpGet("Download/{fileName}")]
    public IActionResult DownloadFile(string fileName)
    {
        // 逻辑代码
    }
}

此时请求地址变为:

  • 获取文件:https://localhost:44427/api/files/ById/123
  • 下载文件:https://localhost:44427/api/files/Download/test.csv

3. 验证路由配置

确认Program.cs中路由中间件顺序正确:

var app = builder.Build();

// 确保UseRouting在UseEndpoints之前
app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

内容的提问来源于stack exchange,提问作者orangejuice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:20:38