【问题标题】:ASP.net MVC 3 - Getting posted JSON data in OnActionExecutingASP.net MVC 3 - 在 OnActionExecuting 中获取发布的 JSON 数据
【发布时间】:2011-02-22 23:16:26
【问题描述】:

我使用 jquery 中的 $.ajax 方法将数据发布到肌动蛋白,使用数据字段指定要发布的数据以传递 JSON 字符串化值。

这些已发布到操作 OK,但我无法在 OnActionExecuting 操作过滤器中获取它们(它们不是 Forms 或 Params 集合的一部分)。有没有办法得到它们,如果没有,你能告诉分享为什么不吗?

【问题讨论】:

    标签: asp.net-mvc json asp.net-mvc-3


    【解决方案1】:

    如果您的操作采用模型:

    [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();
        }
    }
    

    【讨论】:

    • @Steve Ward,您想对您的评论提出一些问题吗?我的回答有什么不清楚的地方吗?
    • 谢谢达林。在这种情况下,此参数不是模型的一部分,因为它提供给每个操作,但从未被操作使用(用于身份验证)。它只是在全局动作过滤器中使用,所以第二种方法似乎是要走的路。我可以从 json 中解析出来,因为这似乎是唯一的方法......
    • 我可以将 json 作为一个简单的字符串发布吗?
    • 在接收Json 格式化数据的WebHook 中声明名为string jsonPayLoad = " "; 的变量而不是string json = " "; 不是很好吗?
    【解决方案2】:
    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])
            );
        }
    }
    

    postedData 变量包含发送到操作的 JSON 格式的数据

    【讨论】:

      猜你喜欢
      • 2017-07-22
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2017-04-29
      相关资源
      最近更新 更多