0

I have this 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. 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? I'm sure that should be a way to get the following line in the controller:

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

2 Answers 2

2

You can use a serializer to serialize the object to a string version. Here is how you will do it with 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. You can include the relevant property values in the string returned by 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.

public void Post(MyClass value)
{
    if(value!=null)
    {
       var stringVersion = value.ToString();
    } 
}
Sign up to request clarification or add additional context in comments.

7 Comments

Why to deserialize and then serialize a json. There must be a way to read the json as it is from the request. (t is possible with WCF, but I haven't used webapi)
@LB, Request.InputStream gives you raw data inside a controller. Outside it, you can get hold of raw data using HttpContext.Current.Request.InputStream. But again, other than logging there may be additional processing on this data for which, accepting it as a model object would be the right way.
@JasonP, You don't need that attribute unless you are using web api.
@JasonP [FromBody] is not necessary for it to work. I just removed it from the answer.
@MatJ In web api it works as well. Why should I use it?
|
0

you can use JavaScriptSerializer to serialize class object into json object like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.