using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Grass.Extend;
namespace Grass.Mvc.Infrastructure.Filter
{
public class WebApiActionDebugFilter : System.Web.Http.Filters.ActionFilterAttribute
{
/// <summary>
/// 是否开启调试
/// </summary>
private bool _isDebugLog = true;
public string DebugId
{
set
{
var session = System.Web.HttpContext.Current.Session;
if (session != null)
{
session["RequestDebugId"] = value;
}
}
get
{
var session = System.Web.HttpContext.Current.Session;
if (session != null && session["RequestDebugId"]!=null)
{
return session["RequestDebugId"].ToString();
}
return string.Empty;
}
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
{
base.OnActionExecuting(context);
//记录请求内容
if (_isDebugLog)
{
try
{
var guid = System.Guid.NewGuid().ToString();
DebugId = guid;
var session = System.Web.HttpContext.Current.Session;
var request = System.Web.HttpContext.Current.Request;
var keys = request.Form.AllKeys;
var task = context.Request.Content.ReadAsStreamAsync();
var content = string.Empty;
using (System.IO.Stream sm = task.Result)
{
if (sm != null)
{
sm.Seek(0, SeekOrigin.Begin);
int len = (int) sm.Length;
byte[] inputByts = new byte[len];
sm.Read(inputByts, 0, len);
sm.Close();
content = Encoding.UTF8.GetString(inputByts);
}
}
string pars = string.Format("请求:\r\n id = {3};\r\n sessionId = {0};\r\n url = {1};\r\n contentType = {4};\r\n content = {2};"
,""// (session==null)?"...":session.SessionID
, request.RawUrl
, content
, guid
, request.ContentType);
}
catch (Exception ex)
{
}
}
}
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)
{
base.OnActionExecuted(context);
//记录请求内容
if (_isDebugLog)
{
try
{
var session = System.Web.HttpContext.Current.Session;
var task = context.Response.Content.ReadAsStringAsync();
var txt = task.Result;
string pars = string.Format("响应:\r\n id = {2};\r\n sessionId = {0};\r\n response = {1}"
, ""//(session == null) ? "..." : session.SessionID
, txt
, DebugId);
}
catch (Exception ex)
{
}
}
}
}
}
c# .net mvc webapi Filters 筛选器中获取 请求参数和响应内容
原创
©著作权归作者所有:来自51CTO博客作者xxj_jing的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C# HttpClient请求Webapi帮助类json .net get请求 post请求 json格式
-
svn本地仓库的创建
一, 单仓储的svn服务器搭建二, 多仓储的svn服务器搭建三, 权限的分配四, 开启svnserve的方法 #####################单仓储的svn服务器搭建########################参考内容:**svn
svn本地仓库的创建 SVN服务器搭建 SVN多项目管理 SVN权限配置 SVNserve自启动设置方法