Linux上ASP.Net Core Web API中未处理的异常

亚伦·拉姆福德

我有一个带有单个节点的ASP.Net Core 3.1 WebAPI。(从本质上讲,这是一个代理终结点,不必在此链的最后端处理噩梦般的白名单。)我同样控制的客户端,都以编程方式将相同的请求发送到代理。有时或经常,Kestral服务器在Linux服务器的系统日志中报告以下错误。

Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:       An unhandled exception has occurred while executing the request.
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]: Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Unexpected end of request content.
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMeta
data metadata, Object value)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]: --- End of stack trace from previous location where exception was thrown ---
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boo
lean isCompleted)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isComple
ted)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Oct  2 19:06:52 CCBD-Status-API-East CCBD-Status-API[979]:    at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

要求很小

{'Url': '<URL data>', 'Status': 0}

API控制器代码:

public IActionResult GetStreamStatus([FromBody] StreamInfo input)
{
    try
    {
        if (!ModelState.IsValid) return BadRequest();
        NetworkCredential netCred = new NetworkCredential(_config.Value.User, _config.Value.Pass);
        var cred = new CredentialCache();
        cred.Add(new Uri(input.Url), "Digest", netCred);
        _logger.LogInformation($"Attempting to get status from: {input.Url}");
        var httpClient = new HttpClient(new HttpClientHandler {Credentials = cred, PreAuthenticate = true});
        var resp = httpClient.GetAsync(new Uri(input.Url));
        _logger.LogInformation($"{input.Url} returned: {resp.Result.StatusCode}");
        input.Status = (int) resp.Result.StatusCode;

        return Ok(input);
    }
    catch (Exception e)
    {
        _logger.LogError(e.ToString());
        return BadRequest();
    }
}

Startup.cs配置方法

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler(a => a.Run(async context =>
    {
        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
        var exception = exceptionHandlerPathFeature.Error;

        var result = JsonConvert.SerializeObject(new {error = exception.Message});
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(result);
    }));

    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });

    app.UseRouting();

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

编辑:添加客户端代码

def check_stream(tc, app, feed, server):
    try:
        logger.info("Check Stream: {}".format(server))
        stream_url = ""
        if server == 'pri':
            stream_url = <Building URL>
        elif server == 'bak':
            stream_url = <Building URL>

        json_input = {"Url": stream_url, "Status": 0}
        logger.info(json_input)
        headers = {'Content-Type': 'application/json'}

        resp = requests.post(<Proxy URL>, data=json.dumps(json_input),
                             headers=headers)
        
        logger.info(resp.headers)
        logger.info("Response Text: {}".format(resp.text))
        results = json.loads(resp.text)
        code = results.get('status')

        return code
    except Exception as e:
        logger.error("Stream Check exception: {} {}".format(type(e).__name__, str(e.args)))
亚伦·拉姆福德

我想到了。我将节点更改为异步,并且该节点正常工作。

public async Task<IActionResult> GetStreamStatusAsync([FromBody] StreamInfo input)
{
    try
    {
        if (!ModelState.IsValid) return BadRequest();
        NetworkCredential netCred = new NetworkCredential(_config.Value.User, _config.Value.Pass);
        var cred = new CredentialCache();
        cred.Add(new Uri(input.Url), "Digest", netCred);
        _logger.LogInformation($"Attempting to get status from: {input.Url}");
        var httpClient = new HttpClient(new HttpClientHandler {Credentials = cred, PreAuthenticate = true});
        var resp = await httpClient.GetAsync(new Uri(input.Url));
        _logger.LogInformation($"{input.Url} returned: {resp.StatusCode}");
        input.Status = (int) resp.StatusCode;

        return Ok(input);
    }
    catch (Exception e)
    {
        _logger.LogError(e.ToString());
        return BadRequest();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类常见问题

使用VSTS的ASP.NET Core Web API的CI / CD

来自分类Dev

是否需要完整的示例来使用ASP.NET Web Api中的“ ExceptionHandler”处理未处理的异常?

来自分类Dev

使用NLog在ASP.NET Web API 2.1中进行全局异常处理?

来自分类Dev

ASP.NET(C#)Web服务中的异常处理

来自分类Dev

当前Web请求的执行期间发生未处理的异常。ASP.NET

来自分类Dev

通过Lambda表达式引发异常时如何在ASP.NET Web API中全局处理异常

来自分类Dev

ASP.NET Core 1.0 Web API不返回XML

来自分类Dev

禁用ASP.NET Web API 2中的* all *异常处理(为我自己腾出空间)?

来自分类Dev

如何从Web API调用ASP.NET Core Web MVC

来自分类Dev

ASP.NET Core 1.0 Web API使用camelcase

来自分类Dev

ASP.NET Core Web Api自动帮助页面

来自分类Dev

使用Web API的ASP.Net Core路由

来自分类Dev

在Asp.net Core中将字典发布到Web API

来自分类Dev

具有请求/响应模式的ASP.NET Core Web API异常处理

来自分类Dev

Web API请求未处理Asp.net Core 3.1和Axios

来自分类Dev

Odata ASP.NET Core 2.2 Web API分页

来自分类Dev

ASP.NET Core Web API和角色授权

来自分类Dev

从ASP .NET Core Web API方法返回完整的XML响应

来自分类Dev

ASP.NET Core Web API InvalidOperationException:无法解析服务

来自分类Dev

asp.net core 2 Web API超时问题

来自分类Dev

在本地托管Asp.net Core Web Api

来自分类Dev

将LAN上的设备连接到ASP.NET Core Web API

来自分类Dev

如何从Web API调用ASP.NET Core Web MVC

来自分类Dev

当前Web请求的执行期间发生未处理的异常。ASP.NET

来自分类Dev

通过Web Api和ASP.NET Core搜索数据库上的项目

来自分类Dev

ASP .Net Core Web 应用程序调用 Web API

来自分类Dev

我如何在 asp.net web api 项目而不是 .net core 上使用 DI

来自分类Dev

调试asp.net core web API

来自分类Dev

如何正确处理 ASP.Net Core 3 Web API 中的多个端点

Related 相关文章

  1. 1

    使用VSTS的ASP.NET Core Web API的CI / CD

  2. 2

    是否需要完整的示例来使用ASP.NET Web Api中的“ ExceptionHandler”处理未处理的异常?

  3. 3

    使用NLog在ASP.NET Web API 2.1中进行全局异常处理?

  4. 4

    ASP.NET(C#)Web服务中的异常处理

  5. 5

    当前Web请求的执行期间发生未处理的异常。ASP.NET

  6. 6

    通过Lambda表达式引发异常时如何在ASP.NET Web API中全局处理异常

  7. 7

    ASP.NET Core 1.0 Web API不返回XML

  8. 8

    禁用ASP.NET Web API 2中的* all *异常处理(为我自己腾出空间)?

  9. 9

    如何从Web API调用ASP.NET Core Web MVC

  10. 10

    ASP.NET Core 1.0 Web API使用camelcase

  11. 11

    ASP.NET Core Web Api自动帮助页面

  12. 12

    使用Web API的ASP.Net Core路由

  13. 13

    在Asp.net Core中将字典发布到Web API

  14. 14

    具有请求/响应模式的ASP.NET Core Web API异常处理

  15. 15

    Web API请求未处理Asp.net Core 3.1和Axios

  16. 16

    Odata ASP.NET Core 2.2 Web API分页

  17. 17

    ASP.NET Core Web API和角色授权

  18. 18

    从ASP .NET Core Web API方法返回完整的XML响应

  19. 19

    ASP.NET Core Web API InvalidOperationException:无法解析服务

  20. 20

    asp.net core 2 Web API超时问题

  21. 21

    在本地托管Asp.net Core Web Api

  22. 22

    将LAN上的设备连接到ASP.NET Core Web API

  23. 23

    如何从Web API调用ASP.NET Core Web MVC

  24. 24

    当前Web请求的执行期间发生未处理的异常。ASP.NET

  25. 25

    通过Web Api和ASP.NET Core搜索数据库上的项目

  26. 26

    ASP .Net Core Web 应用程序调用 Web API

  27. 27

    我如何在 asp.net web api 项目而不是 .net core 上使用 DI

  28. 28

    调试asp.net core web API

  29. 29

    如何正确处理 ASP.Net Core 3 Web API 中的多个端点

热门标签

归档