从ExceptionLogger引用操作参数

Jef*_*Fay 8 asp.net-web-api asp.net-web-api2

我想要使​​用新方法来记录全局日志错误.我编写了一个继承ExceptionLogger并覆盖该Log()方法的类.然后将其注册为替代品.

public class TraceExceptionLogger : ExceptionLogger
{
    public async override void Log(ExceptionLoggerContext context)
    {
        //  This is always empty string
        var content = await context.Request.Content.ReadAsStringAsync();

        //  This is almost always null
        var actionContext = context.ExceptionContext.ActionContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以挖掘ExceptionLoggerContext对象的属性来获取我需要的所有东西,除了动作参数.确实有一个ActionContext属性,但我只看到它为null,这个维基页面说明ActionContext并且ControllerContext几乎总是为空.

此外,我无法获取内容流,因为它的流已经在它到达我的记录器之前被读取.所以我无法从请求的内容中获取任何发布的json.

有没有办法从HttpContext.Current其他方式获取发布的数据?

Jef*_*Fay 7

好吧,看起来我可以通过在Request对象上读取InputStream来获取HttpContext中的正文文本,如下所示:

string bodyText = string.Empty;

using (var sr = new StreamReader(HttpContext.Current.Request.InputStream))
{
    sr.BaseStream.Seek(0, SeekOrigin.Begin);
    bodyText = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这段代码已成功获取我发布的json数据.


Who*_*ver 5

这是将来参考的动作参数

public class HomeController : ApiController {
    public string Get(string id, [FromHeader] Whoever whoever) {

    public string Post(Whatever whatever) {


var args = ((ApiController) context.ExceptionContext
           .ControllerContext.Controller)).ActionContext.ActionArguments

if (args.ContainsKey("whatever")) {
   var whatever = (Whatever)args["whatever"];
Run Code Online (Sandbox Code Playgroud)