Home > Software engineering >  How to read JSON Value in ASP.Net Controller
How to read JSON Value in ASP.Net Controller

Time:07-04

How can I get value of "request_id" from the JSON Field inside my ASP.Net Core Controller ?

{"request_id":"5nRJwCgt95yfmq9qVPrzei16568823342584","number":"90001000000","price":0.028}

I need to assign value of "request_id" to string ReqID;

My Controller code as follows

        public async Task<ActionResult> RequestAuthenticate() {
            var client = new RestClient("https://api.mysmsprovider.com/v1/verify");
            var request = new RestRequest("",Method.Post);
            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", "api_secret=123M&api_key=84545&code_length=4&from=NBL&to=90000001", ParameterType.RequestBody);
            RestResponse response = client.Execute(request);

            return Ok(response.Content);
        }

CodePudding user response:

you have to parse response.Content

using Newtonsoft.Json;

string ReqID= JObject.Parse(response.Content)["request_id"].ToString();

CodePudding user response:

ASP.NET MVC already handles this. Put the model as a param to the action method.

For example, create a model the includes the data you are interested in receiving with properties matching the JSON fields:

public class MyData {
    public string request_id {get;set;}
}

And the controller

public class MyController {
    public Result MyActionMethod(MyData myData) {
        // now myData.request_id contains 5nRJwCgt95yfmq9qVPrzei16568823342584
        // you can use it/assign it to whatever you want
        var ReqID = myData.request_id;
    }
}

Edit:

If you already have the JSON as a string, you can manually deserialize it into an object as follows:

var myData = Newtonsoft.Json.JsonConvert.DeserializeObject<MyData>(json);
// now myData.request_id will be the value you expect.
var ReqID = myData.request_id;
  • Related