Getting web API path from swagger - c#

I have swagger URL http://somehost/swagger/index.html
end methods there as shown on image:
As someone said to me http://somehost/api/Referral/GetReferralByNumber is API address which I can refer it by HTTP request.
static void Main(string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
string result = client.DownloadString("http://somehost/api/Referral/GetReferralByNumber");
}
catch (System.Net.WebException ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
this is code for testing API, but
System.Net.WebException: The remote server returned an error: (404)
Not Found exception
is thrown. any help?

Client.DownloadString() makes an GET request. Your action supports POST. Try to use HttpClient, it should be better for your case.

You are hitting a Get Request and for Get request there is no such endpoint.
You should try adding the HTTP option Post to the server.
Code:
private static readonly HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/referral/GetReferralByNumber", data);
Where data is the data which should be posted to the server.

You should create an http client and use POST like this:
var method = HttpMethod.Post;
var endPoint = "http://somehost/api/Referral/GetReferralByNumber";
var request = new HttpRequestMessage(method, endPoint);
var client = new HttpClient();
var response = await httpClient.SendAsync(request);

Related

How do I fix the Problem Error 404 from Webclient

Hey guys,
I have a problem with my code. Since about a week my code is not working anymore without any changes. I am pretty sure, that my could should work. All I get is Error 404: forbidden.
Below is a snippet of my Code. I also read about adding a header of the webclient, which did not help. Any other suggestions? I am sorry if my syntax is not that good, it is my first post on stackoverflow.
Thanks in advance!
string epicId = "ManuelNotManni";
WebClient webClient = new WebClient();
Uri uri = new Uri("https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/");
string result = String.Empty;
try
{
string website = $"{uri.ToString()}{epicId}?";
result = webClient.DownloadString(website);
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
webClient.Dispose();
}
This is the exact error:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at System.Net.WebClient.GetWebResponse(WebRequest request)
at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream)
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at TestProject.Program.Main(String[] args) in > C:\Users\Manue\source\repos\TestProject\Program.cs:line 17
You're right. Your code should work fine.
Issue is that URL you're requesting which is actually:
https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/ManuelNotManni?
This returns a 403 status code in any case - no matter if you use a browser, your code or for example postman.
I suggest to have a look at the response body while using postman.
It shows this
<html class="no-js" lang="en-US">
<!--<![endif]-->
<head>
<title>Attention Required! | Cloudflare</title>
<meta name="captcha-bypass" id="captcha-bypass" />
Tracker.gg wants API users to register their apps with them before they're given access to the API.
What you need to do is to first head to their Getting Started page. Here you will have to create an app, which should give you an authentication key.
When you have done this, you want to change your code slightly to add the Authentication Header. Like so for example:
var webClient = new WebClient();
webclient.Headers.Add("TRN-Api-Key", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
As a sidenote, WebClient has been deprecated and it's recommended to use HttpClient from now on. Here's your code with HttpClient instead:
var epicId = "ManuelNotManni";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("TRN-Api-Key", "YOUR API KEY GOES HERE");
// Simplifying Uri creation:
var uri = new Uri($"https://api.tracker.gg/api/v2/rocket-league/standard/profile/epic/{epicId}");
var result = string.Empty; // C# prefers lowercase string
try
{
var response = await httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
Console.WriteLine($"Unable to retrieve data for {epicId}.");
Console.WriteLine($"Statuscode: {response.StatusCode}");
Console.WriteLine($"Reason: {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error:\n{ex}");
Console.ReadLine();
}
finally
{
httpClient.Dispose();
}
This happens when we violate the Firewall rule set by Cloudflare, you can visit this blog for more details.
https://community.cloudflare.com/t/community-tip-fixing-error-1020-access-denied/66439

I got a System error in C# post

It is my first time to ask a question in here (I'm from Asia).
Platform:UWP 17632
IDE : Visual Studio 2017
Based on the reqiurement of the project, I need to post some information to a website.
I refer the answer about How to make HTTP POST web request Method A.
Here is my code:
public async void PostDataAsync(string pTemperture, string pHumidity, string pFireStatus, string pLightStatus, string pBodyStatus)
{
var values = new Dictionary<string, string>
{
{"count", "1" },
{"temperture_0", pTemperture },
{"Humidity_0", pHumidity },
{"FireStatus_0", pFireStatus },
{"LightStatus_0" ,pLightStatus},
{"BodyDetect_0", pBodyStatus }
};
var content = new FormUrlEncodedContent(values);
try
{
var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);//Here throw an exception
System.Diagnostics.Debug.WriteLine(response);
var responseString = response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.HelpLink);
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}
And then it throws an exception
“An error occurred while sending the request.”
in
var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);
I want to know why and gain the solution which can solve it.
I will be grateful if you can help me.
It is recommend that use HttpClient and the rest of the Windows.Web.Http namespace API to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols within UWP.
For your requirement, you could make a method to package http POST method like the follow
public async void SendPostMethod(string url, Dictionary<string, string> param, Action<string> response)
{
HttpClient client = new HttpClient();
HttpResponseMessage httpResponse = new HttpResponseMessage();
Uri requestUri = new Uri(url);
var content = new HttpFormUrlEncodedContent(param);
try
{
httpResponse = await client.PostAsync(requestUri, content);
response(await httpResponse.Content.ReadAsStringAsync());
}
catch (Exception ex)
{
}
}
Usage
this.SendPostMethod("http://115.159.36.210/api/onehome/upload",Param, (res) =>
{
var response = res;
});
And there are official code sample and document that you could refer.
I am the author of the server.
The reality is I have not finish the code of the server.
Thus , {"status":-1,"msg":"Error! Invalid Request."} is the default result .....

A HttpRequest Redirect Exception in UWP Project

The code goes below
public static async Task<string> getForwardUrl(string url)
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage forwardRequest = new HttpRequestMessage();
forwardRequest.RequestUri = new Uri(url);
HttpResponseMessage Message = await client.SendAsync(forwardRequest);
return Message.RequestMessage.RequestUri.OriginalString;
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
//...
}
When I run this in a uwp project, exception occurs. The message of this exception shows that the redirection request would change the safe connection to an unsafe one(After that , I checked the URL of the login page , It's https ,but the page after I logged in is http).
I find a similar question, he recommends using Windows.Web.Http instead of System.Net.Http but I get the same error message.
Thanks for your reply
EDIT:
The URL is: https://tinyurl.com /57muy (remove the space) or short a http url with tinyurl.com! The problem only occurs with a shortet http side!
Error: An error occurred while sending the request. Innermessage: Error message not found for this error
According to your description, I'd suppose you are developing a UWP app. And as you've mentioned, we got the exception here because the redirection request would change the safe connection to an unsafe one. To solve this problem, we can turn off auto-redirect and do the redirection by ourselves.
For example:
public static async Task<string> getForwardUrl(string url)
{
var handler = new System.Net.Http.HttpClientHandler();
handler.AllowAutoRedirect = false;
var client = new System.Net.Http.HttpClient(handler);
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.Redirect || response.StatusCode == System.Net.HttpStatusCode.Moved)
{
return response.Headers.Location.AbsoluteUri;
}
return url;
}

HTTPWebRequest GET request causing SSL connection issue

I am trying to connect to a RESTful API and when I access the URL from my browser I get an error stating I am missing headers which is what I was expecting to get. When I connect to the same URL using the below code I get an error stating "The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream". If I use the same code and change the URL to Google.com it works fine and to add to the mystery the connection I make to the API URL from my browser will generate an entry in the Apache logs on the API server, but the below code doesn't. Does anyone have any ideas why I would get that error?
var httpWebRequest = (HttpWebRequest)WebRequest.Create("HTTPS://URL.COM");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
string html = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Response.Write(responseString);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
UPDATE: I tried using HttpClient and got the same results:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://url.com/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("v1/person").Result;
if (response.IsSuccessStatusCode)
{
Response.Write(response);
}
else
{
Response.Write(response);
}
UPDATE 2: The below line of code seems to fix the problem. I am awaiting confirmation now. I am still a little baffled why this was required though.
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

ASP.Net Web API Request URI Error

I have an ASP.Net Web API that generally works fine. I have a Winforms client application that does GET requests. The client application runs on our corporate network (the API is hosted as an Azure Website). Occasionally, and inconsistently, the HttpClient calls I make add what seem to be corporate URLs in front of my GET call.
Example: I try to call send an HttpClient request to the following URL: 'http://xyzxyz.azurewebsites.net/api/user/1'
but the actual request made is:
'http://usgaabc1iru01/B0000D0000N0001F0000S0000R0004/http://xyzxyz.azurewebsites.net/api/user/1'
This obviously causes an error.
I've asked our IT department what may be happening and they are at a loss. Hoping someone could point me in the right direction.
Edit:
Here's the code I use. First I have a static method I call everything I make a call to the API to get the HttpClient (is this awkward/bad perhaps):
public static HttpClient GetHttpClient()
{
var credentials = new NetworkCredential(GlobalVariables.CurrentUser.UserName, GlobalVariables.CurrentUser.Password);
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = false;
handler.Credentials = credentials;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(PublicClasses.GlobalVariables.BaseUriString);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
GlobalVariables.CredentialedHttpClient = client;
}
return GlobalVariables.CredentialedHttpClient;
}
}
Here's a simple GET call I use:
public static List<Project> GetAllProjects()
{
try
{
HttpClient client = GetHttpClient();
HttpResponseMessage response = client.GetAsync("api/project").Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
var projects = response.Content.ReadAsAsync<IEnumerable<Project>>().Result;
return (List<Project>)projects;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}
catch (Exception)
{
throw;
}
}
I don't have an answer for why is this happening but I came across similar issue in a web form (not a win forms client). That is solved by using base meta tag.I am not sure if that solves your problem, but you can give a try.
You can use base address with HttpClient like this (if you are not already doing this):
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://xyzxyz.azurewebsites.net/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/user/1");
if (response.IsSuccessStatusCode)
{
//add your code
}
}

Categories