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)
{
}
}
}

}
}