Referencing Action Parameters from ExceptionLogger

只谈情不闲聊 提交于 2019-11-30 03:33:19

问题


I'm wanting to make use of the new method for globally logging errors. I've written a class that inherits ExceptionLogger and overrides the Log() method. Then registered it as a replacement.

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;
    }
}

I can dig through the ExceptionLoggerContext object's properties to get pretty much everything I need, EXCEPT for action parameters. There is indeed an ActionContext property but I've only seen it null and this wiki page states that ActionContext and ControllerContext will almost always be null.

Also, I can't get the content stream because its stream is already read before it gets to my logger. So there's no way for me to get any posted json from the request's content.

Is there maybe a way to get the posted data from HttpContext.Current or in some other way?


回答1:


Ok it looks like I can get the body text from HttpContext by reading InputStream on the Request object like this:

string bodyText = string.Empty;

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

This code has been successful me so far for getting my posted json data.




回答2:


Here's action parameters for future reference

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"];


来源:https://stackoverflow.com/questions/22971395/referencing-action-parameters-from-exceptionlogger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!