calling a Asp.net web API from c# with multiple of parameters - c#

I have a web api that has parameters. I am trying to call the api from another application. This is not a problem on the client side using, but i cannot find a way to do it on the server side in c#. Thanks for any advice.

You can call Web API from any desktop or server side application using WebClient.
var webClient = new WebClient();
webClient.Headers["Content-Type"] = "application/json";
webClient.Headers["X-JavaScript-User-Agent"] = "Google APIs Explorer";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { longUrl = url });
var data = webClient.UploadString("https://www.googleapis.com/urlshortener/v1/url?pp=1", json);

http://weblogs.asp.net/pglavich/archive/2012/02/18/mvc4-and-web-api-make-an-api-the-way-you-always-wanted-part-1.aspx
The link above worked perfectly for me.

Related

Streaming large file across multiple layers

Large zip file (in gigabytes) is stored in API layer. When a user clicks download button in the browser the request goes through WEB tier to the API tier and in return we need to stream the large file from API tier to WEB tier back to the client browser.
Please advice how can I stream large file from API application to WEB application to client without writing the file in web application?
The Web application request API applications using rest sharp library, it would be great if you can advice a solution using rest sharp (alternatively native code). Both the projects are in .NET core 2.2
Are you looking for DownloadData?
https://github.com/restsharp/RestSharp/blob/master/src/RestSharp/RestClient.Sync.cs#L23
The following is directly from the example in the docs:
var tempFile = Path.GetTempFileName();
using var writer = File.OpenWrite(tempFile);
var client = new RestClient(baseUrl);
var request = new RestRequest("Assets/LargeFile.7z");
request.ResponseWriter = responseStream =>
{
using (responseStream)
{
responseStream.CopyTo(writer);
}
};
var response = client.DownloadData(request);
Found the solution by using HttpClient instead of RestSharp library for downloading the content directly to browser
The code snippet is as below
HttpClient client = new HttpClient();
var fileName = Path.GetFileName(filePath);
var fileDowloadURL = $"API URL";
var stream = await client.GetStreamAsync(fileDowloadURL).ConfigureAwait(false);
// note that at this point stream only contains the header the body content is not read
return new FileStreamResult(stream, "application/octet-stream")
{
FileDownloadName = fileName
};

POST request implementation

I need to implement a post request in a c# winform application of my project. Earlier to that I just have implemented get requests. I have checked that the API URI is working well (I checked it using Postman). I never implemented POST requests in the past. The get requests I implement using the following code:
WebClient n = new WebClient();
string uri = "API_URI";
string json = n.DownloadString(uri);
Now my requirement is to download json string using post method with an "apikey" with its value which I need to provide while calling the URI.
When I am using the above code, it is searching the "API_URI" in my local application directory.
Any direction, sample code and or tutorial will be much appreciated. Please help me with that.
Since you have the call tested in Postman, as a starting point use the "Code" link in PostMan to generate your call using RestSharp so that you can test it and further refine it.
https://learning.getpostman.com/docs/postman/sending-api-requests/generate-code-snippets/
you can do something like this:
WebClient client = new WebClient();
string uri = "API_URI";
string json = "{some:\"json data\"}";
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add("Authorization", "apikey");
string response = client.UploadString(uri,json);
this is the documentation https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstring?view=netframework-4.8
You can use POST method in this way
WebClient client = new WebClient();
string uri = "API_URI";
var reqparm=new NameValueCollection(); // Used for passing request perameter
reqparm.Add("some","json data");
response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", reqparm));
I hope this will help you.

Using Azure Hybrid Connection to connect to internal Web API

Very new to Azure, and I have an internal web API on an internal address http://internal-server:182/api/policies. I have set up a Hybrid Connection internal-service.servicebus.windows.net. This is connected and working.
My struggle is getting the C# code working to connect and retrieve the data. After a number of days, I have reviewed various articles, videos etc and all seem more advanced than what I am trying to do, which is just call the Web API and read the JSON. I have tried to simplify the code but receive the error:
401 MalformedToken: Invalid authorization header: The request is missing WRAP authorization credentials.
At present I have the followed code:
using (var client = new HttpClient())
{
var url = "http://internal-service.servicebus.windows.net";
var tp = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "<key goes here>");
var token = tp.GetWebTokenAsync(url, string.Empty, true, TimeSpan.FromHours(1))
.GetAwaiter()
.GetResult();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ServiceBusAuthorization", token);
var response = client.GetAsync("/api/policies").Result;
string res = "";
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
Label1.Text = res;
}
}
Any help or direction would be much appreciated? Once this code is working the Web App will be published as an Azure Web App.
Seems that your are not sending the right header.
First suggestion: intercept the call with a proxy like fiddler, to do that add a proxy config to your call to localhost port 8888, after this you can try some request and see the raw http you are sending to the server, you can also modify it until it works, once you have this modify your code until it send the same raw http.
You can find more info about this here:
Microsoft Azure CreateQueue using Simple REST Client
https://github.com/ytechie/event-hubs-sas-generator

"The remote name could not be resolved" error when calling API from server

On my website I have some calls to an API.
In client side, with AJAX, it works perfectly but from server side (MVC and C#) I'm getting the following error:
The remote name could not be resolved 'api.website.com'
This is the code that calls the API:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var data = JsonConvert.SerializeObject(email);
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var resp = client.UploadString(#"http://api.website.com/functions/email", data);
Any help would be very much appreciated.
As #neuhaus wrote, the problem was due to a DNS setting, once it had been fixed it worked fine.

Webservice in GAE, call from a C# client

I have created a webapplication on Google App Engine that gets and sets data in datastore, using Python API and it's working fine.
Now I want to access to that data from a client application, written in C# so I was thinking of creating a webservice in GAE to provide access to the data to my app.
I have started to play a bit with ProtoRPC, and built a "hello" webservice as in the tutorial and now I want to call that webservice from my C# client application.
I have found Jayrock lib which seems to do the job; unfortunately I can't find how to make it work.
Here is my code, based on JayrockRPCClient sample :
JsonRpcClient client = new JsonRpcClient();
client.Url = "http://localhost:8081/hello";
JsonObject p = new JsonObject { { "my_name", "Joe" } };
Console.WriteLine(client.Invoke("hello.hello", p));
I always get Missing value error.
Can anybody point me to what do I do wrong ?
And as another question, what do you think of that architecture, as there a simplier way to build a webservice in GAE and call it from C#?
Note that while ProtoRPC communicates via JSON, it is not a JSON-RPC service. By using a JSON-RPC client, you are most likely sending messages in the wrong format.
You should be doing a POST to http://localhost:8081/hello.hello with a request body of {"my_name": "Joe"}. Check to make sure your client is sending requests in this format.
Using WebClient:
var uri = new Uri("http://localhost:8081/hello.hello");
var data = "{\"my_name\":\"Joe\"}";
var wc = new WebClient();
wc.Headers["Content-type"] = "application/json";
wc.Encoding = Encoding.UTF8;
var response = wc.UploadString(uri, data);
For serializing objects, you can use DataContractJsonSerializer.

Categories

Resources