代码之家  ›  专栏  ›  技术社区  ›  Rob Lyndon

ASP.NET核心:请求返回200 OK,无内容:控制器未实例化

  •  0
  • Rob Lyndon  · 技术社区  · 6 年前

    我正在尝试运行一个ASP.NET核心服务器。我的服务器请求返回200 OK,但是没有内容返回,根据我所能得到的,控制器甚至没有被实例化。

    来自Azure流日志的最后一个输入如下所示:

    应用程序:2018-07-20 13:42:13.294+00:00[debug]microsoft.aspnetcore.routing.tree.treerouter:request成功匹配名为“(null)”且模板为“api/culture/notificationsreceived/uptoutc/take”的路由。 应用程序:2018-07-20 13:42:13.670+00:00[debug]microsoft.aspnetcore.server.kestrel:connection id“0hlfe8pani4tl”已完成保持活动响应。 应用程序:2018-07-20 13:42:13.670+00:00[信息]microsoft.aspnetcore.hosting.internal.webhost:请求完成时间:413.5636ms 200

    因此,路由匹配,请求完成,但我尝试将断点附加到控制器(远程调试器附加,但从未命中任何断点,即使在我的中间件中),并将来自控制器的信息记录如下:

    [<Authorize>]
    [<Route("api/{culture}/[controller]")>]
    type NotificationsReceivedController(notifications: IReceivedNotifications, logger: ILog) =
        inherit Controller()
        do logger.Information "NotificationsReceivedController" "Created controller" None
    
        [<HttpGet("{upToUtc}/{take}")>]
        [<ProducesResponseType(200, Type = typeof<PageOfNotifications>)>]
        member this.Get(upToUtc:int64, take:int) =
            async {
                let upToUtc = new DateTime(upToUtc, DateTimeKind.Utc)
                logger.Information "NotificationsReceivedController" "GetReceivedNotifications endpoint" None
                let! notifications = notifications.GetAsync this.HttpContext upToUtc take
                return this.Ok(notifications) :> IActionResult
            } |> Async.StartAsTask
    

    我不明白假阳性。如果我的管道出了问题,为什么日志中没有记录?如果没有什么问题,为什么路径匹配,但是控制器没有被实例化?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rob Lyndon    6 年前

    我用异常过滤器解决了这个问题

    type ApiError = {
        ErrorType: Type
        Message: string
        StackTrace: string
    }
    
    type ApiExceptionAttribute(logger: ILog) =
        inherit ExceptionFilterAttribute()
        static let [<Literal>] Tag = "ApiExceptionAttribute"
        override __.OnException(context) =
            base.OnException context
            context.HttpContext.Response.StatusCode <-
                match context.Exception with
                | As (_: UnauthorizedAccessException) -> HttpStatusCode.Unauthorized |> int
                | _ -> HttpStatusCode.InternalServerError |> int
            let ex = context.Exception.GetBaseException()
            let apiError = {
                ErrorType = ex.GetType()
                Message = ex.Message
                StackTrace = ex.StackTrace
            }
            logger.Error Tag (apiError.ToString()) (Some ex)
            context.Result <- JsonResult apiError
    

    然后,按照标准实践,我在 Startup.fs 文件:

    在我的startup.fs文件中:

    services.AddMvc(fun config -> 
        config.RespectBrowserAcceptHeader <- true
        config.Filters.Add<ApiExceptionAttribute>() |> ignore
    ) |> ignore
    

    这解决了我的误报,并允许我跟踪和修复代码中的错误。