从内容类型application / JSON的请求检索值 [英] Retrieve a value from a request with content type application/json

查看:228
本文介绍了从内容类型application / JSON的请求检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的脚本,在MV​​C将数据发送到控制器:

I have the following script that is sending data to a controller in MVC:

$.ajax({
    url: '/products/create',
    type: 'post',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        'name':'widget',
        'foo':'bar'
    })
});

我的控制器看起来是这样的:

My controller looks like this:

[HttpPost]
public ActionResult Create(Product product)
{
    return Json(new {success = true});
}

public class Product 
{ 
    public string name { get; set; }
}

有没有一种方法我可以在我的控制器行动foo的变量,而不

Is there a way I can get the "foo" variable in my controller action without


  • 修改模型

  • 修改动作的签名

如果这是一个普通的表单提交,我将有机会获得的Request.Form [富],但由于它是通过应用程序/ JSON提交该值为空。

我希望能够从一个行为过滤器访问这个值,这就是为什么我不希望修改签名/模式。

I want to be able to access this value from an Action Filter and that is why I don't want to modify the signature/model.

推荐答案

我想今天一样做几乎一模一样,发现没有回答这个问题。我也与类似的解决方案马克解决了这个问题。

I wanted to do almost exactly the same today and found this question with no answer. I also solved it with similar solution as Mark.

这工作得非常好,我在asp.net MVC 4.也许可以帮助别人阅读,即使它是一个古老这个问题。

This works very well for me in asp.net MVC 4. Could maybe help someone else reading this question even if it is an old one.

        [HttpPost]
        public ActionResult Create()
        {
            string jsonPostData;
            using (var stream = Request.InputStream)
            {
                stream.Position = 0;
                using (var reader = new System.IO.StreamReader(stream))
                {
                    jsonPostData = reader.ReadToEnd();
                }
            }
            var foo = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonPostData)["foo"];

            return Json(new { success = true });
        }

的重要组成部分,是因为它已经被一些MVC内部code或任何阅读重置流的位置。

The important part was to reset the position of the stream because it is already read by some MVC internal code or whatever.

这篇关于从内容类型application / JSON的请求检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆