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

C# ASP.NET Core Web API远程服务器错误返回403而非预期404

问题排查:接口无结果时日志返回404但客户端收到403

本地调试时,调用GetEntityReport接口无结果会返回HTTP 404,符合预期;部署到远程服务器后,日志显示请求返回404,但实际客户端收到403错误。当查询有结果时,接口可正常返回200 OK。

问题控制器代码

namespace ReportServices.Controllers
{
    private readonly IReportServiceRepo _repository;
    private readonly IMapper _mapper;
    private readonly ILogger<ReportServicesController> _logger;

    public ReportServicesController(IReportServiceRepo repository, IMapper mapper, ILogger<ReportServicesController> logger)
    {
        _repository = repository;
        _mapper = mapper;
    }

    // GET api/reportservice/entities/{id}/2022/11/test
    [AllowAnonymous]
    [HttpGet]
    [Route("entities/{entityId:int}/{year:int:maxlength(4)}/{month:int:maxlength(2)}/{title}", Name = "GetEntityReport")]
    [ProducesResponseType(typeof(IList<ReportReadSimpleDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult<IList<ReportReadSimpleDto>> GetEntityReport(int entityId, int year, int month, string title)
    {
        var reportsItem = _repository.SearchForReport(entityId, year, month, title);

        if (reportsItem != null && reportsItem.Count > 0)
        {
            return Ok(_mapper.Map<IEnumerable<ReportReadSimpleDto>>(reportsItem));
        }

        return NotFound("No report found for this criteria.");
    }
}

日志信息

Request starting HTTP/1.1 GET              
    https://www.skagitcounty.net/Apps/REST/ReportService/api/reportservice/entities/1/2021/1/test

Request finished HTTP/1.1 GET         
    https://www.skagitcounty.net/Apps/REST/ReportService/api/reportservice/entities/1/2021/1/test - - - 404 - text/plain;+charset=utf-8 38.6428ms 

Swagger查询截图

Swagger查询截图

远程服务器已安装.NET 8托管包,以下是具体排查思路:

  • 检查IIS错误页配置:查看站点的“错误页”设置,确认404状态的处理方式是否被修改,比如是否将404重定向到需要权限的页面,导致客户端收到403。确保404响应的状态码未被自定义规则篡改。
  • 验证URL重写规则:检查IIS的URL重写模块,排查是否存在针对该接口路径的重写规则,当返回404时触发了权限校验逻辑,导致状态码变为403。
  • 确认.NET托管配置:检查应用程序池的设置,确保“.NET CLR版本”设置为“无托管代码”(ASP.NET Core应用需此配置),同时验证.NET 8托管包是否正确注册到IIS中。
  • 排查安全拦截机制:检查服务器上的防火墙、Web应用防火墙(WAF)或安全软件,确认是否将特定场景下的404响应判定为异常请求,进而拦截并返回403。
  • 检查站点文件权限:确认IIS应用程序池标识拥有站点物理路径的读写权限,避免因权限不足导致404响应被异常处理为403。
  • 启用详细日志:在远程服务器上开启ASP.NET Core的详细日志记录,跟踪从控制器返回404到客户端接收响应的中间件处理流程,定位是否有中间件修改了响应状态码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:59:55