【问题标题】:HttpRequest describable to stringHttpRequest 可描述为字符串
【发布时间】:2018-08-07 05:34:02
【问题描述】:

我正在使用带有 C# 的 asp.net core v2.1 并制作了一个小型网站。这个网站有ExceptionsTracker 捕获所有未处理的异常。

internal class ExceptionTracker : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        // ...
        string httpRequestInformation;
        try
        {
            httpRequestInformation = context.HttpContext.Request.ToString(); // The problem here.
        }
        catch (Exception)
        {
            httpRequestInformation = string.Empty;
        }
        // ...
    }
}

这背后的主要思想是将所有异常写入日志并能够在开发时重现它(运行产生异常的相同查询)。

当我使用之前的 .NET 框架 (v4.6) 制作这条线时 context.HttpContext.Request.ToString(),返回值是一个字符串,其中包含来自请求的所有信息(请求的 URL、标头、正文等)。当我使用 .net core 进行操作时,返回值为

Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest

你有更好的解决方案然后手动构造这个字符串吗?

谢谢!

更新

根据@kennyzx 的建议,我做了一个简短的方法扩展来解决这个问题。

public static class HttpRequestExtensions
{
    public static string GetDetails(this HttpRequest request)
    {
        string baseUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString.Value}";
        StringBuilder sbHeaders = new StringBuilder();
        foreach (var header in request.Headers)
            sbHeaders.Append($"{header.Key}: {header.Value}\n");

        string body = "no-body";
        if (request.Body.CanSeek)
        {
            request.Body.Seek(0, SeekOrigin.Begin);
            using (StreamReader sr = new StreamReader(request.Body))
                body = sr.ReadToEnd();
        }

        return $"{request.Protocol} {request.Method} {baseUrl}\n\n{sbHeaders}\n{body}";
    }
}

如果您有更好的解决方案,请告诉我。

【问题讨论】:

    标签: c# asp.net asp.net-core .net-core


    【解决方案1】:

    你得到

    一个字符串,包含来自请求的所有信息(请求的 URL、标头、正文等)。

    通过在 v4.6 中调用 ToString(),因为该类覆盖了 System.Object.ToString() 方法,但在 asp.net core v2.1 中没有,所以它只打印类的完整限定名,这是默认值System.Object.ToString() 的返回值。

    您可以自己做,通过从它提供的various properties 构造字符串。你可以写一个extension methodlike

    public static class MyExtensionClass 
    {
        public static string GetDetails(this Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest request)
        {
            return request.PathString.Value + " " + ... ; //Construct your string here 
        }
    }
    

    并像使用它

    httpRequestInformation = context.HttpContext.Request.GetDetails(); 
    

    【讨论】:

    • 此解决方案是“手动”解决方案。它确实有效,但不如以前的解决方案(.net framework v4.6)好。在主线程中附加了我的代码。
    • 我再次检查了我在答案中提供的链接,已经为此类定义了一些扩展方法,例如 GetDisplayUrl,因此您可以使用现有方法来增强您的方法。但是如果你真的想在一个方法中获得这么多详细的信息,你必须自己写。
    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多