WebApi在过滤器中获取帖子原始内容 [英] WebApi get the post raw body inside a filter

查看:71
本文介绍了WebApi在过滤器中获取帖子原始内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建日志,我需要检索请求正文以保存在db中.我用HttpActionContext创建了一个过滤器. 我尝试通过filterContext.Request.Content.ReadAsStringAsync().Result;恢复; 但它总是返回一个空字符串.

I' creating a log and i need to retrieve the request body to save in db. i created a filter with HttpActionContext. I tried recover via filterContext.Request.Content.ReadAsStringAsync().Result; but it always return me an empty string.

LogFilter.cs

LogFilter.cs

public override void OnActionExecuting(HttpActionContext filterContext)
    {
        try
        {
            Task<string> content = filterContext.Request.Content.ReadAsStringAsync();
            string body = content.Result;

            logModel.RequestLog rl = new logModel.RequestLog();
            rl.IP = ((HttpContextWrapper)filterContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            rl.Type = filterContext.ControllerContext.RouteData.Values["controller"].ToString().ToUpper();
            rl.URL = filterContext.Request.RequestUri.OriginalString;
            rl.Operation = filterContext.Request.Method.Method;
            rl.RequestDate = DateTime.Now;


            filterContext.ControllerContext.RouteData.Values.Add("reqID", new deviceLog.RequestLog().Add(rl).ID.ToString());
        }
        catch { }
        //return new deviceLog.RequestLog().Add(rl);
        base.OnActionExecuting(filterContext);
    }

推荐答案

也许请求流已经到达结尾.尝试将流位置重置为开始:

Maybe request stream already reached to end. Try reset stream position to beginning:

public class MyAttribute:ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionContext actionContext)
    {
        string rawRequest;
        using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
        {
            stream.BaseStream.Position = 0;
            rawRequest = stream.ReadToEnd();
        }
    }
}

这篇关于WebApi在过滤器中获取帖子原始内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆