从ExceptionLogger引用操作参数

时间:2014-04-09 18:46:39

标签: 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;
    }
}

我可以挖掘ExceptionLoggerContext对象的属性来获取我需要的所有东西,除了动作参数。确实存在ActionContext属性,但我只看到它为空,this wiki page表示ActionContextControllerContext几乎总是为空。

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

是否有办法从HttpContext.Current或以其他方式获取发布的数据?

2 个答案:

答案 0 :(得分: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();
}

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

答案 1 :(得分: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"];