How to make a JSON Post Request and handle it - c#

I would like to make a Json Post Request to my MVC .NET application api beeing: http://localhost:39622/api/holiday
The Json file should represent the following class:
public class Holiday
{
public string ldapName { get; set; }
public DateTime date {get; set;}
}
I have already initialized an instance of my model class within the "postHoliday" method and converted it to a JSON file.
public void postHoliday()
{
Holiday holiday1 = new Holiday();
holiday1.ldapName = "dkassube";
holiday1.date = new DateTime(2016, 08, 01);
string output = JsonConvert.SerializeObject(holiday1);
WebRequest request = WebRequest.Create("localhost:39622/api/holiday");
request.Method = "POST";
// What to do here?
}
I´m not really sure on how to send the JSON to my API controller and how I can handle the request when it arrives. When the API controller receives the JSON i want to convert it back to an instance of Holiday.
public class HolidayController : ApiController
{
public Holiday handleIncomingHoliday()
{
Holiday incomingHoliday = new Holiday();
// What to do here?
return incomingHoliday;
}
}

Related

Getting data from ASP.NET Core API

I am working on Market and Financial News app.I took the API from https://www.marketaux.com/. I am trying to display the news from the site into my home page. I have created a model file and controller in ASP.NET Core web app file. In controller file, I get an error in response.data part as its showing response doesn't have data object whereas when I print the output of response.Content, it has data object. Can you tell me how to solve this and get access to the data from the API so that I can display it on my Home page?
Controller class:
using System.Runtime.CompilerServices;
using Azure.Core;
using MarketNews.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI;
using Newtonsoft.Json;
using RestSharp;
namespace MarketNews.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class NewsController : ControllerBase
{
[HttpGet]
public News[] GetNews()
{
List<News> news = new List<News>();
RestClient client = new RestClient("https://api.marketaux.com/v1/news/all");
// client.Timeout = -1;
RestRequest request = new RestRequest("News",Method.Get);
request.AddQueryParameter("api_token", "qIWtsblpK93oeo23o87egUGBoVmVaqkl4fdHRTEc");
request.AddQueryParameter("symbols", "aapl,amzn");
request.AddQueryParameter("limit", "50");
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
if (response != null)
{
foreach (var article in response.data)
{
news.Add(new News
{
Title = article.title,
Description = article.description,
Url = article.url,
Url_Image = article.image_url,
Published_At = article.published_at
});
}
}
return news.ToArray();
}
}
}
Model class
namespace MarketNews.Models
{
public class News
{
public string Title;
public string Description;
public string Url;
public string Url_Image;
public DateTime Published_At;
}
}
I wanted to get data from the API and display it on my Home Page. I used RestClient and RestRequest to get response and then from response. I got the output when response.Content printed to console, it is working and it gave me a json file as output. In foreach loop when I tried to set the response data to the model data I created, it's showing response.data doesn't exist.
I want to know what is wrong here or is there any other method to get the data from the API?
Api: Website link
From RestSharp documentation, the Execute() method does support for a generic type.
Execute<T>(IRestRequest request)
Note that, this method is deprecated. You shall look for the method below:
ExecuteAsync<T>(IRestRequest request, CancellationToken cancellationToken)
and revamp your API action to support asynchronous operation.
From the response data shared in the link, you need a Root object which contains the data property with the List<New> type.
Define the data model class for the response.
using System.Text.Json;
public class Root
{
[JsonPropertyName("data")]
public List<News> Data { get; set; }
}
public class News
{
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("url")]
public string Url { get; set; }
[JsonPropertyName("image_url")]
public string Url_Image { get; set; }
[JsonPropertyName("published_at")]
public DateTime Published_At { get; set; }
}
For the caller, specify the generic type as Root. Next extract the data property from the response with response.Data.Data.
RestResponse<Root> response = client.Execute<Root>(request);
// asynchronous way
// RestResponse<Root> response = await client.ExecuteAsync<Root>(request);
if (response != null)
news = response.Data.Data;

receiving a json string in C# Web Api 2

I'm trying to do a patch with web api. I keep getting NULL for my json. Please Help
Here is my Json
[{"PartNumber":"AN33016UA-VB"}{"Category":"Chassis"}]
Here is my my class
public class wsCategory
{
public string PartNumber { get; set; }
public string Category { get; set; }
}
Here is my Api Controller
[HttpPatch]
[ActionName("IMDSCategory")]
public HttpResponseMessage IMDSCategory([FromBody]wsCategory jsonbody)
{
var data = jsonbody.PartNumber;
return new HttpResponseMessage(HttpStatusCode.Created);
}
The JSON is inavalid.
[{"PartNumber":"blahblah","Category":"Chassis"}]
I believe the array container will be parsed out correctly, but I'm on a chromebook right now, so I can't check that. If it still fails, drop the [].
based on your method
[HttpPatch]
[ActionName("IMDSCategory")]
public HttpResponseMessage IMDSCategory([FromBody]wsCategory jsonbody){...}
Your JSON is invalid given the model you are trying to parse.
[{"PartNumber":"AN33016UA-VB"}{"Category":"Chassis"}]
should be
{"PartNumber":"AN33016UA-VB","Category":"Chassis"}

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.
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>
If what you are receiving is JSON, you can accomplish this is many ways.
One would be to wrap the code you've posted into a JSON Result typed Action. A very simplistic example below:
[HttpPost]
public JsonResult GetIncidentId(int customerId, string incidentNumber)
{
JsonResult jsonResult = null;
Incident incident = null;
try
{
incident = dal.GetIncident(customerId, incidentNumber);
if (incident != null)
jsonResult = Json(new { id = incident.Id });
else
jsonResult = Json(new { id = -1 });
}
catch (Exception exception)
{
exception.Log();
}
return jsonResult;
}
Calling it via Javascript from the view and manually populating your form (meh).
Or more elegantly, you could create an MVC model to hold the data you receive and serialise the JSON into that model. An example of which is below:
From: http://www.newtonsoft.com/json/help/html/deserializeobject.htm
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Hope this helps and good luck with your app!

How to correctly deserialise JSONArrays using RestSharp

How do I correctly deserialise the results of this call (you can click to see output):
https://bitpay.com/api/rates
I'm using a POCO object like this:
public class BitpayPrice
{
public string code { get; set; }
public string name { get; set; }
public double rate { get; set; }
}
And I'm calling the API like so:
var client = new RestClient();
client.BaseUrl = "https://bitpay.com";
var request = new RestRequest("/api/rates", Method.GET);
var response = client.Execute<BitpayPrice[]>(request);
Now, I know that the call to execute is wrong, but how do I un-wrongify it? I'd like to get back an array of BitcoinPrice objects.
RestSharp doesn't support deserializing into array, the best you can get is a List<>:
var response = client.Execute<List<BitpayPrice>>(request);
The reason is that types that you can deserialize to are required to have public parameterless constructor (for performance reasons mostly).

RestSharp: Converting results

I get the following JSON that I am trying to convert to a business object using RestSharp
{
"valid":true,
"data":[
{
"dealerId":"4373",
"branchId":"4373",
}
]
}
I wish to convert to:
public class Dealer
{
public string dealerId ;
public string branchId;
}
But this fails, though the JSON is fine:
var client = new RestClient("http://www.????.com.au");
var request = new RestRequest(string.Format("service/autocomplete/dealer/{0}/{1}.json", suburb.PostCode, suburb.City.Trim().Replace(" ", "%20")), Method.GET);
var response2 = client.Execute<Dealer>(request);
return response2.Data;
Your business object doesn't match the response JSON you are getting back. If you want your response to serialize, your C# object would look something like
public class DealerResponse
{
public bool valid { get;set; }
List<Dealer> data { get;set; }
}
public class Dealer
{
public string dealerId;
public string branchId;
}
I haven't tested this code, but even though you are only interested in the information in 'data', your response C# objects still need to represent the whole JSON response to serialize correctly.
Hope that helps.

Categories