Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Good evening,
I am new in c# and asp.net
I have created an MVC 4 WEB Application and I am using aspx as the view.
I am trying to call a remote web API and unfortunately I do not get it, in order to display the data on my web site.
I created one controller and inside the controller in the Index() method I wrote this code:
public class CallAPIController : Controller
{
//
// GET: /CallAPI/
public async Task<string> Index()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://remoteWEBAPI/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/data").Result; // Blocking call!
string json = await response.Content.ReadAsStringAsync();
Debug.WriteLine("Content: " + json);
return json;
}
}
I am new to this technologies, I have tried many things and I have been struggling with this for the last 4-5 hours.I do not know how to solve this problem. Could you please help me? I do not think it should be very difficult for someone expert familiar with these...
Assuming your WebAPI accepts GET method and returning a JSON string.
WebClient client = new WebClient();
client.Headers["Accept"] = "application/json";
string returnedString = client.DownloadString(new Uri("http://yourwebapi.com/api/data"));
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to teach myself how to make simple API calls with C#. I'd like to call this "http://hivemc.com/json/userprofile/da10b68dea6a42d58ea8fea66a57b886". This should return some strings in json but I don't know what i'm supposed to do with that.
reference: https://apidoc.hivemc.com/#!/GameData/get_game_game_data_id_UUID
I'm new to programming and I've never done anything with API's. I've tried looking around the internet but I don't understand what I'm supposed to look for. Can someone refer me to an article that can teach me how to do this? I have no idea where to start. An example of the code with explanation would be great but I understand if it's too much to ask.
Thank you!
You can start from the following.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Test
{
public static void Do()
{
var result = GetGameData("da10b68dea6a42d58ea8fea66a57b886").Result;
//TODO parse json here. For example, see http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c
Console.WriteLine(result);
}
private static async Task<string> GetGameData(string id)
{
var url = "http://hivemc.com/json/userprofile/" + id;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string strResult = await response.Content.ReadAsStringAsync();
return strResult;
}
else
{
return null;
}
}
}
}
Sample call
Test.Do();
You should use System.Net.HttpClient from Nuget. Check this link out. It shows you how to get data from the API. The next step is to deserialize it to your model using Newtonsoft.Json.
Hope it helps!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm developing a small application that has to interact with a JSON/REST service.
What is the easiest option to interact with it in my c# application.
I don't need to have the best performances, since it's just a tools that will do some synchronization once a day, I'm more oriented toward the ease of use and the time of development.
(the service in question will be our local JIRA instance).
I think the best way by far is to use RestSharp. It's a free Nuget Package that you can reference. It's very easy to use and this is the example from their website:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a desktop application that has some classes, which I want to serialize and send to a webpage when a user clicks a button in the desktop C# application.
The data is too long for an argument. What I want to achieve here is, how do I post it and open the website on the clients PC with the dynamic changes made by the sent data ?
Need some suggestions or guidance to proceed in the right direction.
You can use HttpClient
For example:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://myUrl");
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
//do something
}
}
One option would be to generate local page with form that contains data and "action=POST" pointing to your site. Than set script that automatically submit this form and as result you'll have data send by browser and browser will continue as if it is normal POST request.
If you don't like HttpClient you can also use WebClient which is a convenience wrapper for your exact scenario.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an ASP.NET MVC site and a Web API.
In a controller action of the MVC site I do:
public ActionResult ActionAsync()
{
string result = MakeAsyncRequest().Result;
return View("Index", (object)result);
}
MakeAsyncRequest() is as follows:
private async Task<string> MakeAsyncRequest()
{
using (var client = new HttpClient())
{
Task<string> response = client.GetStringAsync("http://localhost:55286/api/Home");
DoSomething();
return await response;
}
}
When I debug I see DoSomething() being executed (it's just a void), also the WebAPI gets called and returns a string, but then the return of MakeAsyncRequest doesn't happen and the browser stays indefinitely waiting for the server to return something.
Why is this? Something to do with the client being an ASP.NET MVC site?
.Result
That's a classic ASP.NET deadlock. Don't block. Or, don't use async/await but your case seems like a good fit. Make the action async as well.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
using c#.
I just want to clarify something... I normally work with WCF. Can I call rest apis exactly like I call WCF? Or do I use WebClient and parse the responseStream? If the rest api returns string formatted as JSON would I then somehow format this json in the responseStream?
I have spent sometime Googling but there seems to be different advice for it.
to be specific are there any standards for rest api clients? Is it just down to choice?
You should look into HttpClient (For making REST calls) and Json.NET (For serializing / deserializing your json):
A simple Get request:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(uri);
//will throw an exception if not successful
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<SomeType>(content);
Note HttpClient is built with an asynchronous API which preferably should be used with async/await keywords