![](/img/trans.png)
[英]ASP.NET MVC: Execute code on all Actions (global OnActionExecuting?)
[英]ASP.net MVC 3 - Getting posted JSON data in OnActionExecuting
我使用jquery中的$ .ajax方法将数据发布到肌动蛋白,指定要使用数据字段发布的数据以传递JSON字符串化值。
这些被发布到操作OK但我无法在OnActionExecuting操作过滤器中获取它们(它们不是Forms或Params集合的一部分)。 有没有办法得到它们,如果没有,你能告诉分享为什么不呢?
如果您的操作采用模型:
[HttpPost]
public ActionResult About(SomeViewModel model)
{
return Json(model);
}
您可以直接使用此参数值,因为JsonValueProviderFactory已经解析了它:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
SomeViewModel model = filterContext.ActionParameters["model"] as SomeViewModel;
}
如果没有模型(为什么不存在?),您可以从请求流中读取JSON:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
filterContext.HttpContext.Request.InputStream.Position = 0;
using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
protected override void OnActionExecuting(ActionExecutingContext ctx) {
//All my viewDto end with "viewDto" so following command is used to find them
KeyValuePair<string, object> dto = ctx.ActionParameters.FirstOrDefault(item =>
item.Key.ToLower().EndsWith("viewdto")
);
string postedData;
if (dto.Key != null) {
object viewData = dto.Value;
if (dto.Key.ToLower() == "viewdto") {
var stdStoryViewDto = dto.Value as StandardStoryViewDto;
//removing unnecessary stuff
stdStoryViewDto.Industries.Clear();
stdStoryViewDto.TimeZones.Clear();
viewData = stdStoryViewDto;
}
postedData = JsonConvert.SerializeObject(viewData);
} else {
postedData = string.Join(",",
Array.ConvertAll(ctx.ActionParameters.Keys.ToArray(),
key => key + "=" + ctx.ActionParameters[key])
);
}
}
postingData变量包含发送到操作的JSON格式的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.