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); }
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;
you have to parse response.Content
using Newtonsoft.Json; string ReqID= JObject.Parse(response.Content)["request_id"].ToString();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.