C# 如何将 JSON 文件发布到 ASP.NET MVC 操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15317856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:24:14  来源:igfitidea点击:

How do you post a JSON file to an ASP.NET MVC Action?

c#asp.netasp.net-mvc

提问by aryaxt

My iphone client posts the following json to my mvc service. When posting data from html form it automatically converts form data to UserModel and passes the object to my Create method, but when I send the JSON string in the body of my request from iphone it comes back as null.

我的 iphone 客户端将以下 json 发布到我的 mvc 服务。从 html 表单发布数据时,它会自动将表单数据转换为 UserModel 并将对象传递给我的 Create 方法,但是当我从 iphone 发送请求正文中的 JSON 字符串时,它返回为空。

What would be the cleanest solution to do the conversion from JSON to Object.

从 JSON 到 Object 的转换最干净的解决方案是什么?

I rather not create multiple methods for different clients, so I'm trying to get the same method to work on iphone, and mvc client.

我宁愿不为不同的客户端创建多种方法,所以我试图让相同的方法在 iphone 和 mvc 客户端上工作。

Body of my request:

我的请求正文:

{
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}

My Model and Action Result

我的模型和行动结果

public class UserModel
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
}

[HttpPost]
public Create ActionResult(UserModel user)
{
   // user is null
   userStorage.create(user);
   return SuccessResultForModel(user);
}

采纳答案by Glenn Ferrie

You need to set the HTTP Header, accept, to 'application/json' so that MVC know that you as passing JSON and does the work to interpret it.

您需要将 HTTP 标头 accept 设置为“application/json”,以便 MVC 知道您正在传递 JSON 并执行解释它的工作。

accept: application/json

see more info here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

在此处查看更多信息:http: //www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

UPDATE:Working sample code using MVC3 and jQuery

更新:使用 MVC3 和 jQuery 的工作示例代码

Controller Code

控制器代码

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PostUser(UserModel data)
        {
            // test here!
            Debug.Assert(data != null);
            return Json(data);
        }
    }

    public class UserModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

View Code

查看代码

@{ ViewBag.Title = "Index"; }
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    var sample = {};
    sample.postData = function () {
        $.ajax({
            type: "POST", url: "@Url.Action("PostUser")",
            success: function (data) { alert('data: ' + data); },
            data: { "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" },
            accept: 'application/json'
        });
    };
    $(document).ready(function () {
        sample.postData();
    });
</script>

<h2>Index</h2>

回答by Jesse Jin

Try to change the method to this to see if you get FirstName or LastName

尝试将方法更改为此以查看您是否获得 FirstName 或 LastName

public Create ActionResult(string FirstName, string LastName)

回答by David Ulvmoen

Late but hope it helps someone.

迟到但希望它可以帮助某人。

What would be the cleanest solution to do the conversion from JSON to Object?

从 JSON 到 Object 的转换最干净的解决方案是什么?

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

$.post("http://localhost:52161/Default/PostRawJson/", { json: {
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}});


public void PostRawJson(string json)
{
    var person = System.Web.Helpers.Json.Decode(json);
    person.firstname...
}

This way you get a pure JSON object to work with in your controller as requested.

通过这种方式,您可以根据要求在控制器中使用纯 JSON 对象。

回答by Dustin

I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model [JsonObject] for your controller to get the values and do the conversion.

我最近想出了一种更简单的方法来发布 JSON,另外还有一个步骤是从我的应用程序中的模型进行转换。请注意,您必须为控制器创建模型 [JsonObject] 才能获取值并进行转换。

Request:

要求:

 var model = new MyModel(); 

 using (var client = new HttpClient())
 {
     var uri = new Uri("XXXXXXXXX"); 
     var json = new JavaScriptSerializer().Serialize(model);
     var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
     var response = await Client.PutAsync(uri,stringContent).Result;
     ...
     ...
  }

Model:

模型:

[JsonObject]
[Serializable]
public class MyModel
{
    public Decimal Value { get; set; }
    public string Project { get; set; }
    public string FilePath { get; set; }
    public string FileName { get; set; }
}

Server side:

服务器端:

[HttpPut]     
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
    ...
    ... 
}

回答by codeulike

Based on Glenn Ferries answer, which seemed to work until I looked at what was actually being sent to the controller - and it wasn't JSON.

基于 Glenn Ferries 的回答,在我查看实际发送到控制器的内容之前,这似乎有效 - 它不是 JSON。

Hence adjusted a bit below:

因此在下面进行了一些调整:

This is with MVC 4, and jQuery 1.7 ish

这是 MVC 4 和 jQuery 1.7 ish

Controller action method (UserModel object as in question):

控制器操作方法(有问题的 UserModel 对象):

[HttpPost]
public ActionResult Create(UserModel user)
{
    Debug.Assert(data != null);
    return Json(data);
}

jQuery code to send the request:

发送请求的jQuery代码:

<script>
    $(function () {
        $.ajax({
            type: "POST",
            url: "@Url.Action("Create")",
            /* jQuery will not send JSON unless you explicitly tell it to */
            data: JSON.stringify({ "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" }),
            /* contentType is important for MVC to be able to unpack the json */
            contentType: 'application/json'
            accept: 'application/json',
        }).done( function(data) {
            /* this callback gets used when successful */
            console.log("response: " + data);
        }).fail(function (jqxhr, status, error) {
            /* for debugging: this callback gets used in case of errors */
            console.log("error :" + error);
        }).always(function () {
            /* for debugging: this callback always gets called at the end either way*/
            console.log("complete");
        });
    });

</script>

The MVC controller action is the easy bit.

MVC 控制器操作很简单。

The hard bit is making sure you actually are sending JSON to it to test it.

难点在于确保您确实将 JSON 发送给它以对其进行测试。

jQuery ajax() method when used with POST will generally encode parameters using querystring format in the body of the request. MVC can happily unpack that.

与 POST 一起使用的 jQuery ajax() 方法通常会在请求正文中使用查询字符串格式对参数进行编码。MVC 可以很高兴地解开它。

To actually send JSON with ajax() you must use JSON.stringify().

要实际使用 ajax() 发送 JSON,您必须使用 JSON.stringify()。

And for MVC to correctly interpret that request, you need to set the contentType

为了让 MVC 正确解释该请求,您需要设置 contentType