just starting to create an API to my a web application using the ASP.NET MVC4 Web API project template. http://www.asp.net/mvc/mvc4
No problems with the API so far, but I was about to write a small C# app to test the API.
Almost all the sample I can find is using the a class called HttpClient.
Where can I find the HttpClient and how do I install it?
Rather than using the build in HttpClient class of the .NET framework which has a lot of issues when dealing with StatusCodes that are different than the expected ones. I recommend using a library called RestSharp.
It has become .NET Http/Rest client of choice, you can get it here: http://restsharp.org/
It is a very powerful library that is perfectly suited to do what you want.
It's on nuget, search for HttpClient
http://nuget.org/packages/System.Net.Http
Use WebRequest as described here
// Create a new 'Uri' object with the specified string.
Uri myUri =new Uri("http://www.contoso.com");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest= WebRequest.Create(myUri);
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse= myWebRequest.GetResponse();
If its a REST interface use RestSharp but you would need XSD first.
If the class is not available from your code, then you could download it from a NuGet package, like described in the article:
http://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
or you can try to locate it inside the namespace: System.Net.Http
There is also an example for you wich should get you started!
Related
When diposing an HttpClient, one can run into the "socket exhaustion" problem. So the standard advice is to reuse the client whenever possible.
So I was surprised to find the official Blazor templates (dotnet new blazorwasm) have this scoped factory in Program.cs:
builder.Services.AddScoped(sp =>
new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
I'm even using the IDisposableAnalyzers analyser library that specifically checks for such things, and it warns to replace that line with a single instance.
Why is the template written that way?
This is what I've found.
It has long been recommended to reuse an HttpClient, due to the socket exhaustion problem.
But Blazor's HttpClient doesn't use TCP for connections, it uses the browser's Fetch API instead. And the Fetch API, according to MDN is JavaScript-based:
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
So the original problem doesn't exist, which means we can safely use as many HttpClient instances as we want.
Which is why the Blazor templates use a factory to create multiple instances.
TL;DR: it should be safe.
My only concern is that the above is based on the Blazor docs, but the framework docs for HttpClient do not mention this special behaviour for Blazor. (I wonder how this works - maybe the Blazor SDK has a different implementation for HttpClient than the server SDK?)
If my analysis is wrong, please let me know.
I am creating a new Asp.Net Core (net standard 2) Mvc controller that uses a WebAPI (REST) call to obtain the data. I was following many of the examples shown all over the Interweb from both microsoft and non-microsoft sources. These all use the "standard" using(var client = new HttpClient()) construct.
However, then read the documentation for HttpClient
HttpClient is intended to be instantiated once and re-used throughout
the life of an application. Instantiating an HttpClient class for
every request will exhaust the number of sockets available under heavy
loads. This will result in SocketException errors. Below is an example
using HttpClient correctly.
This got me thinking, do I create a scoped instance and add it to DI, or follow their example on the same page, and create a static instance on the controller? If a static instance, how do I dispose it?
Alternately, can anyone point me to a production ready MVC wrapper for a standard CRUD view implementation?
If you have not read "You're using HttpClient wrong and it is destabilizing your software".
If you have any kind of load at all you need to remember these two
things:
Make your HttpClient static.
Do not dispose of or wrap your HttpClient in a using unless you explicitly are looking for a particular behavior (such as causing your services to fail).
I agree with mike z DI can be used in this case.
e.g. SimpleInjector's Singleton is taking care of disposing.
Simple Injector guarantees that instances are disposed in opposite
order of creation.
If you still want to wrap it, look at "Generic wrapper for calling ASP.NET WEB API REST service using HttpClient with optional HMAC authentication"
Upd:
Make sure you dispose of instances of both of HttpRequestMessage and HttpResponseMessage. See example of usage
Source: http://faithlife.codes/blog/2017/03/usage-guidelines-for-httpclient/
For anyone using .net core 2.1 or greater it is recommended to use HttpClientFactory
To address those mentioned issues and make the management of HttpClient instances easier, .NET Core 2.1 introduced a new HttpClientFactory that can also be used to implement resilient HTTP calls
See microsoft docs on how it can be leveraged.
I use the HttpClient in System.Net.Http to make requests to a web service as below:
using (var client = new HttpClient())
{
using (var response = client.GetAsync(url).Result)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
I have a sandbox application and a live application. The sandbox application has identical code (in a shared repository) which works fine, but when client.GetAsync(url).Result is called in the live application, for some reason Fiddler shows me that the requested URL has been encoded which messes the request up.
Requested URL is supposed to look like this:
/advert?paginate=1&page=1&language=en&filters[updated_at][ge]=2016-03-21%2012:19:05
But ends up looking like this:
/advert?paginate=1&page=1&language=en&filters%5Bupdated_at%5D%5Bge%5D=2016-03-21%2012:19:05
Any idea why? Thanks
N.B. Im using the Microsoft.Net.Http library from Nuget in .NET Framework 4.5
Please be very specific about your question:
you use Microsoft.Net.Http version what?
you compile under .NET version what?
Turned out that you compile under .NET 4.0 and this is a bug I would say, because the behavior is not identical to the .NET Fx 4.5 System.Http
You can fix it by setting dontEscape to true in the Uri class:
var url = new Uri(#"http://google.com/advert?paginate=1&page=1&language=en&filters[updated_at][ge]=2016-03-21%2012:19:05", dontEscape: true);
I am trying to find the nearest store given a zip code. I came to know that yelp and foursquare provides the required APIs to do this. I am using .NET 3.5 framework. How do you make the http requests and handle the responses.Most of the solns on the web give it for .NET 4.5 onwards which includes the usage of HTTPClient class.
You can use System.Net.WebClient class to make an http request.
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin#admin.com\",\"Password\": \"pass#123\"}")));
There are also other methods which can be used, but that depends on your requirements. You can find more details here
from MSDN.
I am trying to connect to Magento API using C#. I am using Magento Go service and from what I've read I am able to use their API - I hope I am not wrong here. So here is what I did:
I added a Service Reference to http://mydomain.gostorego.com/api/v2_soap?wsdl=1, and just adding a service worked fine. Now I created a test class with GetStuff() method, which looks like this:
using ww.Feeds.MagnetoGoService;
public static string GetStuff()
{
MagnetoGoService.Mage_Api_Model_Server_V2_HandlerPortTypeClient s = new MagnetoGoService.Mage_Api_Model_Server_V2_HandlerPortTypeClient();
var login = s.login("username here", "key here");
return login.ToString();
}
When I run the program I get an error in first line saying:
Could not find default endpoint element that references contract 'MagnetoGoService.Mage_Api_Model_Server_V2_HandlerPortType' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
Any ideas what this may be? Do I have to set something up in my Magento Go settings? Or maybe using Magento Go is not allowing API access?
Thanks a lot.
Forget SOAP with c# you will pull your hair out. Download Charls Cook's xml-rpc api libary for c# and use the xml-rpc method. You won't get all the snazzy intellisense but at least it will work. There's also c# solution from ez.newsletter they released with Cook's library demonstrating how to use 80% of the magento api calls.
Cook's library xml-rpc.net
http://www.xml-rpc.net/
ez.newsletter solution
http://code.google.com/p/csharlibformagexmlrpcapi/
If anyone ever has problems with this, my solution was this:
I used the reference in one project, but I actually called the class and had main program in another project. You need your Service reference to be in each project wherever you're using it. That fixed it! Alternatively you can create a new BasicHttpBinding() and putt all the options from app.config/web.config into that binder, then you don't need to reference to Service everywhere. I hope that helps!