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
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to post datetime into the below api. But it is not going through.
lastRefreshDateTime.Result is datetime
Below is the code I tried:
await client.PostAsync($"{_printApiUrl}pdf/GenerateAndEmailZipOfPDFs/${lastRefreshDateTime.Result}", content, cancellationToken);
[Authorize]
[Route("api/pdf/GenerateAndEmailZipOfPDFs/{lastRefreshDateTime}")]
public void GenerateAndEmailZipOfPDFs([FromBody]List<UrlObject> urls,DateTime lastRefreshDateTime)
You are most likely experiencing a deadlock by mixing a blocking call like .Result in an async function.
You need to use await.
var lastRefreshDateTime = await _contentManagement.GetLastRefreshDateTime(cancellationToken);
Reference Async/Await - Best Practices in Asynchronous Programming
Also note how the URI is generated using $ - string interpolation
var uri = $"{_printApiUrl}pdf/GenerateAndEmailZipOfPDFs/{lastRefreshDateTime}";
await client.PostAsync(uri, content, cancellationToken);
There was an errant $ in the shown URI that would cause the date time to be malformed when posted.
Should also consider using a route constraint
[Authorize]
[Route("api/pdf/GenerateAndEmailZipOfPDFs/{lastRefreshDateTime:datetime}")]
public void GenerateAndEmailZipOfPDFs(
[FromBody]List<UrlObject> urls,
[FromRoute]DateTime lastRefreshDateTime
)
Reference Routing to controller actions in ASP.NET Core
Reference Routing in ASP.NET Core
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 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
Currently working with Unity, this might a super basic question, but here goes.
I need to call a URL from my app in C#. This is done for analytics purposes, and so I don't want to open a web browser or anything, just call the URL and that's it. I know about Application.OpenURL() to open the browser, but how do I achieve this without opening the browser ?
You may try like this:
var client = new WebClient();
var x = client.DownloadString("http://example.com");
or
HttpWebRequest request = WebRequest.Create("http://example.com") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
Use the WebClient class in the System.Net namespace.
It's a high level implementation of an HTTP client which is really easy to use.
Has a method called .DownloadString() which does exactly what you want - calls a URL using HTTP GET and returns the response as a string.
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"));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I thought I could do i straight forward, but maybe there is something wrong with my setup? I'm trying to download a string in my app for logging in:
private async void DoLogin()
{
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(Config.SERVER_URL + "/Login/");
All logic is removed, im going to add headers and so on, but VS2012 will no allow me to await that response.
I tried to follow the code from here, but in my case I only get Cannot await 'System.Threading.Tasks.Task<string'.
Why is that? Should'nt GetStringAsync simply return me a string? It returns a Task<string>, but do I have to wrap it in a method?
Your code is perfectly fine. However: In order to use async / await in portable class libaries you need to add the NuGet package Microsoft.Bcl.Async to your project.
Also please note the comment of Servy to use the return type Task instead of void.