我试图访问传递给动作过滤器OnActionExecuted中的视图的模型数据.有谁知道这是否可能?
我想做这样的事情:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//get model data
//...
sitemap.SetCurrentNode(model.Name);
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
我有一个名为Log的属性,它尝试将请求和响应的内容记录到文本文件中.我把它放在我的控制器上以涵盖所有动作.在LogAttribute中,我正在将内容读取为字符串(ReadAsStringAsync),因此我不会丢失请求正文.
public class LogAttribute : ActionFilterAttribute
{
// ..
public override void OnActionExecuting(HttpActionContext actionContext)
{
// stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// other stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
// ..
}
Run Code Online (Sandbox Code Playgroud)
另一方面,我在我的动作参数类之前放置了FromBody属性以利用它的好处.
[Log]
public class SomethingController
{
public HttpResponseMessage Foo([FromBody] myModel)
{
// something
}
}
Run Code Online (Sandbox Code Playgroud)
问题是ActionExecuting或ActionExecuted中的内容始终为空.
我认为这是因为FromBody在我的Log属性之前运行,而不像它们在代码中的顺序.我再次认为是因为根据动作参数(路径处理)找到了请求的最佳动作/控制器匹配.之后我的请求正文被清除,因为请求正文在WebApi中是非缓冲的. …
我ActionFilterAttribute在按下控制器之前用来获取请求,如下所示:
public override void OnActionExecuting(HttpActionContext actionContext)
{
using (var stream = new MemoryStream())
{
HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法适用于小的请求但是对于一个大的json,它给了我这个错误:
在HttpRequest.GetBufferedInputStream的调用者填充内部存储之前,访问了BinaryRead,Form,Files或InputStream.
输入流会出现此错误
context.Request.InputStream引发了System.InvalidOperationException类型的异常System.IO.Stream {System.InvalidOperationException}
正如我在研究中发现的那样,这是超时问题,但我无法更改代码中的超时.我试图改变这些值在web.config文件maxRequestLength="102400000"和maxAllowedContentLength="209715100",但我仍面临着同样的错误.
如果我读了GetBufferedInputStream但仍然是同一个问题,它只是读取缓冲区的一部分,而不是整个流.
我也试过以下:
Stream InStream;
int Len;
InStream = HttpContext.Current.Request.InputStream;
Len = System.Convert.ToInt32(InStream.Length);
byte[] ByteArray = new byte[Len + 1];
InStream.Seek(0, SeekOrigin.Begin);
InStream.Read(ByteArray, 0, Len);
var jsonParam = System.Text.Encoding.UTF8.GetString(ByteArray);
Run Code Online (Sandbox Code Playgroud)
请注意,如果我设置内容类型application/xml或application/x-www-form-urlencoded它的工作原理,但是如果我将其设置为application/json它会给我这个错误!!
请指教!