可描述为字符串的HttpRequest

No1*_*ver 7 c# asp.net .net-core asp.net-core

我在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;
        }
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

当我使用以前的.NET Framework(v4.6)编写此行时 context.HttpContext.Request.ToString(),返回值是一个字符串,其中包含来自请求的所有信息(请求的URL,标头,正文等)。当我使用.net core时,返回值为

Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest
Run Code Online (Sandbox Code Playgroud)

您有更好的解决方案,然后手动构造此字符串吗?

谢谢!

更新资料

根据@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}";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

ken*_*yzx 4

你得到

包含请求中所有信息的字符串(请求的 URL、标头、正文……)。

在v4.6中通过调用ToString(),因为类重写了System.Object.ToString()方法,但在asp.net core v2.1中则没有,所以它只是打印类的完整限定名,这是System.Object.ToString().

您可以自己完成此操作,通过根据字符串提供的各种属性构造字符串。您可以编写一个扩展方法,例如

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

并像这样使用它

httpRequestInformation = context.HttpContext.Request.GetDetails(); 
Run Code Online (Sandbox Code Playgroud)

  • 我再次检查我在答案中提供的链接,已经有一些扩展方法,例如为此类定义的 GetDisplayUrl,因此您可以通过使用现有方法来增强您的方法。但是,如果您确实想要在一个方法中包含如此多的详细信息,则必须自己编写。 (2认同)