0

How can I get value of request_id from the JSON 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 is 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);
}

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, please see my code added to question which returns json response
@Sulfy I updated my answer to include the case where you handle JSON that you obtain from whatever source (REST API call in your case)
2

you have to parse response.Content

using Newtonsoft.Json;

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.