How do I access the content of an API response? - c#

I've tried implementing the simplest case of this with a call to Mandrill's API using the method "ping." The response should be pong. Using a valid key, the response seems to work. However, I am having trouble accessing the content of the response.
The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MandrillAPI
{
class Program
{
static void Main(string[] args)
{
string ping = "https://mandrillapp.com/api/1.0/users/ping.json";
string key = "?key=123";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ping);
HttpResponseMessage response = client.GetAsync(key).Result;
Console.WriteLine(response.ToString());
Console.Read();
}
}
}
How do I unpack the response from the call? Ultimately, I need to harvest emails from the server using the API, so I'll need to somehow preserve the structure of the json objects so I can access the details of the email.

If you just want to read the response as a string:
string content = response.Content.ReadAsStringAsync().Result
If you want to deserialize to some class (in this case the type MyClass):
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result)

I would use something like JSON.Net to serialize it to a C# object that you can then use.

Related

Returning XML From C# WebAPI (Formatting Issues)

I'm calling an XML API from my C# Web API.
The response from the XML API should be returned to the end user initiating the request.
Currently the formatting appears to be broken. When you call the XML API directly it returns as expected, however, my C# API returns the response as just one 'lump' string.
Do I need to deserialize this into an object to get it to a better output?
using (WebClient wc = new WebClient())
{
wc.BaseAddress = $"https://{urlBase}";
wc.Headers.Add(AuthorizationHeader, authorization);
result = wc.DownloadString(urlPath);
}
return result;
When I look at the calls that the application makes to the XMLAPI using Fiddler I can see that the response from the XMLAPI has the correct formatting applied to it. However, when this is returned from my C# API the formatting appears to be broken.
In the Application_Start I've forced the application to use XMLMediaTypeFormatter over JSON, this does not appear to have worked:
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());
Try following which should return a list of XElement. I can see from the black out code if your results just have innertext or you have attributes as well
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string response = "";
XDocument doc = XDocument.Parse(response);
XElement applist = doc.Root;
XNamespace ns = applist.GetDefaultNamespace();
List<XElement> apps = doc.Descendants(ns + "app").ToList();
}
}
}

Data streaming with restsharp and WebAPI

My aim is to GET and POST files to SP Online.
I have written a WEB API with the two methods. These methods use CSOM to interact with SP Online.
The GET returns the response Ok(array of bytes) to the client and the POST gets the entire file to upload in the request body and performs the upload to Sharepoint Online in chunks.
I've been told that i should use streaming techniques, since the context is an enterprise application with many simultaneous requests. So the GET method should return a stream to the client and the client should send the request as a stream to the POST.
In the client side i'm forced to use the RestSharp library.
So:
1) How to use RestSharp to deal with streams?
2) How can the WebAPI return a stream?
3) Along with the file i send a lot of metadata. How can i upload the file in streaming mode and send the metadata only once?
Client side, the get requires an array of bytes and the post sends an array of bytes along with metadata.
Online i've found too many techniques. Is there a standard one?
There a very basic example. It does not covers all of your questions but this is a point to start.
Client with RestSharp:
(I did small ASP.NET Core 2.0 console Application). Add the following code to your Programm.cs)
using System;
using System.IO;
using RestSharp;
namespace RestSharpClient
{
class Program
{
public const string baseUrl = "http://localhost:58610/api/values"; // <-- Change URL to yours!
static void Main(string[] args)
{
Console.ReadKey();
string tempFile = Path.GetTempFileName();
using (var writer = File.OpenWrite(tempFile))
{
var client = new RestClient(baseUrl);
var request = new RestRequest();
request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);
var response = client.DownloadData(request);
}
Console.ReadKey();
}
}
}
Server
My controlller:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
namespace Server.Controllers { [Route("api/[controller]")]
public class ValuesController: Controller {
// GET api/values
[HttpGet]
public FileStreamResult GetTest() {
var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain")) {
FileDownloadName = "test.txt"
};
}
}
}
Important: Enable CORS. For that add the following line to your Startup.cs before services.AddMvc();
services.AddCors();
How to add metadata:
WebAPI method that takes a file upload and additional arguments

How to get data from API request?

I'm pretty new to C# and this is my first time getting data from an api. I was wondering how do I get or call the data collected in this api request (MakeRequest). Preferably assign the data to a public string. The data from the api request is in json format.
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
public partial class Form1 : Form
{
public async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["seasonId"] = "{string}";
var uri = "https://www.haloapi.com/stats/{title}/servicerecords/arena?players={players}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}
So if the call succeeded, you should have your JSON string returned in the response variable you assign in the last line.
Use your debugger and inspect that variable. If you look at the MSDN doc for your GetAsync() method (Link), you can easily find out that the variable is of the type HttpResponseMessage. This class has an own page here telling you that there's a property Content.
This is your JSON string, now might come the part where you have to do some deserializing. Have fun.

'HttpWebRequest' does not contain a definition for 'GetResponseAsync'

I am new in xamarin and visual studio,I have followed this tuto from microsoft:
enter link description here
to create a cross platform application,but I get this error:
'HttpWebRequest' does not contain a definition for 'GetResponseAsync' and no extension method 'GetResponseAsync' accepting a first argument of type 'HttpWebRequest' was found (a using directive or an assembly reference is it missing * ?)
and this is my code in which I get this error:DataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace shared
{
//This code shows one way to process JSON data from a service
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);
var response = await request.GetResponseAsync().ConfigureAwait(false);
var stream = response.GetResponseStream();
var streamReader = new StreamReader(stream);
string responseText = streamReader.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
}
Please how can I solve it, I checked the HttpWebRequest documentation but I didn't get well the problem
thanks for help
Not sure about HttpWebRequest - but a newer and now recommended way to get data is the following:
public static async Task<dynamic> getDataFromService(string queryString)
{
using (var client = new HttpClient())
{
var responseText = await client.GetStringAsync(queryString);
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
Try that and let me know if it works.

c# sending data to php url

okay so I have a c# console source code I have created but it does not work how I want it to.
I need to post data to a URL the same as if I was going to input it an a browser.
url with data = localhost/test.php?DGURL=DGURL&DGUSER=DGUSER&DGPASS=DGPASS
Here is my c# script that does not do it the way I want to I want it to post the data as if I had typed it like above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["DGURL"] = "DGURL";
formData["DGUSER"] = "DGUSER";
formData["DGPASS"] = "DGPASS";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
}
}
}
I have also triead another method in c# this does now work either
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URI = "http://localhost/test.php";
string myParameters = "DGURL=value1&DGUSER=value2&DGPASS=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/html";
string HtmlResult = wc.UploadString(URI, myParameters);
System.Threading.Thread.Sleep(500000000);
}
}
}
}
I have been trying to figure a way to do this in my c# console for days now
Since what you seem to want is a GET-request with querystrings and not a POST you should do it like this instead.
static void Main(string[] args)
{
var dgurl = "DGURL", user="DGUSER", pass="DGPASS";
var url = string.Format("http://localhost/test.php?DGURL={0}&DGUSER={1}&DGPASS=DGPASS", dgurl, user, pass);
using(var webClient = new WebClient())
{
var response = webClient.DownloadString(url);
Console.WriteLine(response);
}
}
I also wrapped your WebClient in a using-statement so you don't have to worry about disposing it yourself even if it would throw an exception when downloading the string.
Another thing to think about is that you might want to url-encode the parameters in the querystring using WebUtility.UrlEncode to be sure that it doesn't contain invalid chars.
How to post data to a URL using WebClient in C#: https://stackoverflow.com/a/5401597/2832321
Also note that your parameters will not appear in the URL if you post them. See: https://stackoverflow.com/a/3477374/2832321

Categories

Resources