Accessing the raw http request in MVC4

拜拜、爱过 提交于 2019-12-22 09:41:53

问题


There are a lot of questions about accessing the HttpRequest on stackoverflow already, but I have not been able to find one that I can use yet. If somebody could point me to an answer I would be grateful.

My problem is that I want to modify an existing application in the simplest way possible in order to add in full request logging. I'm aware there this can be done with Http modules and IIS logging or using Log4net etc etc. But I don't want to use any of these techniques because the application is unpredictable so I need a solution that does not require any configuration changes at all.

I have added OnActionExecuted to a base controller.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    // todo: log request from filter context ....
    base.OnActionExecuted(filterContext);
}

In the "todo" part above I wish to read the raw http request and save it to a database file. Logging to a database is simple enough but what is the best way to serialize or otherwise convert the http request as a string?

Thank you


回答1:


protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var request = filterContext.HttpContext.Request;
    var inputStream = request.InputStream;
    inputStream.Position = 0;
    using (var reader = new StreamReader(inputStream))
    {
        string headers = request.Headers.ToString();
        string body = reader.ReadToEnd();
        string rawRequest = string.Format(
            "{0}{1}{1}{2}", headers, Environment.NewLine, body
        );
        // TODO: Log the rawRequest to your database
    }
}

Oh and if you start doing that, I hope you have already planned the budget you will need for purchasing additional storage on your servers. Coz if you start logging the entire raw request on each request you're gonna need storage.



来源:https://stackoverflow.com/questions/15241710/accessing-the-raw-http-request-in-mvc4

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