虽然授予的答案提到了 ReadAsStringAsync,但答案没有示例。我遵循了 gdp 的建议,并得出了一个可行的示例...
我创建了一个名为 MessageInterceptor 的类。我只是从 ActionFilterAttribute 派生,它立即开始在控制器获取它之前和控制器完成之后拦截 webAPI 方法调用。这是我的最后一节课。此示例使用 XML 序列化器将请求和响应都获取到 XML 字符串中。这个例子发现请求和响应是填充对象,这意味着反序列化已经发生。从填充模型收集数据并序列化为 XML 字符串是请求和响应的表示,而不是 IIS 发回的实际发布请求和响应。
代码示例 - MessageInterceptor
using System.IO;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Xml.Serialization;
namespace webapi_test
{
public class MessageInterceptor : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var headers = actionContext.Request.Content.Headers.ToString();
var request = actionContext.ActionArguments.FirstOrDefault().Value;
var xml = SerializeXMLSerializer(request, "");
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
var headers = actionExecutedContext.Response.Content.Headers.ToString();
var response = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
var xml = SerializeXMLSerializer(response, "");
}
public static string SerializeXMLSerializer(object o, string nameSpace)
{
string serializedValue;
var writer = new StringWriter();
XmlSerializer serializer = new XmlSerializer(o.GetType(), nameSpace);
serializer.Serialize(writer, o);
serializedValue = writer.ToString();
return serializedValue;
}
}
}