简体   繁体   English

在控制器中以JSON格式获取数据

[英]Get data as JSON in controller

I have this Ajax: 我有这个Ajax:

$.ajax({
        url: "/api/Values",
        dataType: "json",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            Id: "1", Name: "Name1", Family: "Family1"
        }),

No I want to get data in controller so that I can save it to a text file with log4net. 不,我想在控制器中获取data ,以便可以使用log4net将其保存到文本文件中。 Currently I have written this code: 目前,我已编写此代码:

public void PostValues(Class1 cs)
    {
        var data = $"Id = {cs.Id}, Name = {cs.Name}, Family = {cs.Family}";
        Log.Debug($"POST Request, value = {data}");
    }

With model binding I can get data that is bound to class properties like above and then combine them like above. 通过模型绑定,我可以获取绑定到上述类属性的数据,然后像上面那样组合它们。 But I don't want to use this way because I have to go through all class properties. 但是我不想使用这种方式,因为我必须遍历所有类属性。 Is there any way to get data posted to controller as JSON? 有什么方法可以将数据作为JSON发布到控制器吗? I'm sure that should be a way to get the following line in the controller: 我确定这应该是在控制器中获取以下行的方法:

Id: "1", Name: "Name1", Family: "Family1"

You can use a serializer to serialize the object to a string version. 您可以使用序列化程序将对象序列化为字符串版本。 Here is how you will do it with JSON.NET 这是使用JSON.NET的方法

public void Post(Class1 value)
{
    var stringVersion = Newtonsoft.Json.JsonConvert.SerializeObject(value);
    // use stringVersion  now.
}

Another option is to override ToString() in your class and use that as needed. 另一个选择是在类中重写ToString()并根据需要使用它。 You can include the relevant property values in the string returned by ToString() 您可以在ToString()返回的字符串中包含相关属性值

public class MyClass
{
    public int Id { set; get; }
    public string Name { set; get; }
    public string Family{ set; get; }

    public override String ToString()
    {
        return $"Id:{Id},Name:{Name}";
    }
}

Now you can simply call ToString() on your MyClass object. 现在,您可以简单地在MyClass对象上调用ToString()

public void Post(MyClass value)
{
    if(value!=null)
    {
       var stringVersion = value.ToString();
    } 
}

您可以使用JavaScriptSerializer这样将类对象序列化为json对象

 var json = new JavaScriptSerializer().Serialize(cs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM