Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying JSON data acquired from a WebRequest in ASP.NET 5 using MVC 6

this is my first question, so I apologize if I mess up the formatting or do this wrong in general, feel free to give me pointers, I'm always open to learn.

Anyway, my issue at hand is that I have a web application I'm working on using ASP.NET 5 and MVC 6, all up to date, and so far for testing, I've been using the localdb and working with fake data. Now, I have a url, with an API token, and login info, and I am using a WebRequest to get the data and stream it with a StreamReader into a variable, writing it, and then trying to return it.

WebRequest req = WebRequest.Create(@"https://url.fortheapi.com/api/search/things?criteria=" + userInput);
req.Method = "GET";
req.Headers["username"] = "user";
req.Headers["password"] = "password";
req.Headers["token"] = "token";

StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Response.WriteAsync(responseData);

return View(responseData);

Here is where I'm stuck because I am not sure exactly how to pass it to the view as model data, I have no model currently, and I want to make one based on this database and use Entity Framework to work with it like I have been with the localdb. If there's a better way to do it, please feel free to present it. I will accept all the help I can get right now.

like image 332
Alfred Shaker Avatar asked Mar 03 '16 20:03

Alfred Shaker


1 Answers

You need to create POCO classes to represent the data you receive from your api call. Once you get the response data, you may simply use a javascript serialize to deserialize the response to an object of your POCO class. You can pass this to your view.

public async Task<ActionResult> Contact()
{
    var req = WebRequest.Create(@"yourApiEndpointUrlHere");    
    var r = await req.GetResponseAsync().ConfigureAwait(false);              

    var responseReader = new StreamReader(r.GetResponseStream());
    var responseData = await responseReader.ReadToEndAsync();

    var d = Newtonsoft.Json.JsonConvert.DeserializeObject<MyData>(responseData);    
    return View(d);
}

Assuming your api returns json data like this

{   "Code": "Test", "Name": "TestName" }

and you have created a POCO class called MyData which can be used to represent the data coming back from the api. You may use json2csharp to generate your C# classes from the json response you received from your api.

public class MyData
{
   public string Code { get; set; }
   public string Name { set;get;}
   //Add other properties as needed
}

Now your view should be strongly typed to this POCO class

@model MyData
<h2>@Model.Code</h2>
<h2>@Model.Name</h2>
like image 118
Shyju Avatar answered Oct 08 '22 09:10

Shyju