REST request getting blocked? - c#

Using RestRequest to a REST endpoint (Asana). Some machines get the request returned properly and some don't get anything. Doing more troubleshooting I think that the machines that do not get responses have IE as their default browser.
If I test the url manually in a Chrome browser I get the response. If I test in the IE browser then I get a "Do you want to Open or Save" prompt. I=My theory is that an IE setting of somekind is blocking the request with this question and since it is an app it just blocks.
My code is simple:
var client = new RestClient(#"https://app.asana.com/api/1.0/workspaces/99999999999999/tasks/search);
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + asanaToken);
IRestResponse response = client.Execute(request);
How can I get around this?

Related

How To Get OAuth 2.0 Access Token From Postman Using C#

Im trying to make an app that allows you to upload files to dropbox.
I created upload system etc. on this app and created postman page to get Token.
My Postman Auth2.0 Page
When i try to get access token by clicking "Get New Access Token" its works like a charm!
But i dont have any idea to get this token in c# i tried to create php post function but its return this page
my code is this i think im taking wrong url or something please help;
var client = new RestClient("https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=<clientid>&redirect_uri=https%3A%2F%2Foauth.pstmn.io%2Fv1%2Fbrowser-callback");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer <author. code>");
request.AddHeader("Content-Type", "text/plain");
request.AddHeader("Cookie", "locale=en; t=<t>; __Host-js_csrf=<auto-code>; gvc=<gvc>");
var body = #"\";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
print(response.Content);
I get this code by taking the link and clicked code and converted to c# on postman website https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=<clientid>&redirect_uri=https%3A%2F%2Foauth.pstmn.io%2Fv1%2Fbrowser-callback

Problems with Visual Studio c# and Restclient httpwebrequests / Postman

I try to make some httpwebrequests with VS C#. The API on the server works with GET and PATCH requests. First i have tested every request with Postman and everything works fine. Then i try to test it in VS (Export C# Restapi and also with httpwebrequest. The result is that the GET requests works fine but on the PATCH requests i get not response (Timeout). There is no exception. It looks like the server is just waiting.
The RestApi Code from Postman:
var client = new RestClient("https://192.168.10.13/Service.dll/v1/terminal");
client.Timeout = -1;
var request = new RestRequest(Method.PATCH);
request.AddHeader("api_auth", "123456");
request.AddHeader("Content-Type", "application/json");
var body = #"{" + "\n" + #" ""status"": ""service""" + "\n" + #"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The client hangs in Line 11 while waiting on a response. After the timeout the response is empty.
Is it possible to capture the whole request to see whats different between Postman and VS?
Could it be a problem with the validation of the server certificate. I have to delegate the validation to true. But this works with the GET requests.
Im still hanging like my requests. Can someone help me with this problem. I have no idea anymore.

Can not Access a URL using Webrequest

I am trying to get access a URL using .Net but when I run my Program I get the Error The remote server returned an error: (403) Forbidden. Now, the issue is if I click the link http://thisIsMyUR, and enter the user name and password as in the below code. It totally works. I am not able to understand why this exception is coming? Please refer the code below.
Side Note: I am using this sample function below to fire Build of my project in Jenkins Server.
string url = "http://thisIsMyURL";
WebRequest webRequest = WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential("admin", "pass");
WebResponse response = webRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
Other than what was recommended by Bradley Uffner in the comments, you can try to provide an actual user agent during the request. I have seen certain servers which would not respond to requests without that header for some odd perceived security reason.
EDIT: as requested, i'll update with some more information.
Some servers may choose to ignore requests, giving some error code (or closing connection) when certain conditions are not met. A good way of checking if that is the case, is to actually send all the standard headers sent by your average web browser in the request. The "User agent" is one of those headers, and this example adds it to your request:
string url = "http://thisIsMyURL";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.UserAgent = "USER AGENT VALUE";
HttpWebRequest.Credentials = new NetworkCredential("admin", "pass");
WebResponse response = webRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
The cast to HttpWebRequest is required so you have access to the UserAgent header field. Other standard HTTP fields can be accessed this way.
You can check which headers are sent by your browser of choice by inspecting its requests using the browser developer tools (usually Right click on webpage -> Inspect elements -> Network).
I figured it out with the help of some articles. A basic authentication needs to be added. Below is a sample.
var userName = "admin;"
var password = "password";
var encodedAuthentication = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
webRequest.Headers.Add("Authorization", "Basic " + encodedAuthentication);

Getting httpresponse from other site

Need help. I want to get the returned data from this link - http://www.pse.com.ph/stockMarket/companyInfoSecurityProfile.html?method=getListedRecords&common=yes&ajax=true
However, if you copy and paste that link to your browser you get Access Denied ( See Tab Title). But if you paste this link first http://www.pse.com.ph ( load the page) then paste again the link above you data.
Here is my code. I am using RestSharp
string url = "http://www.pse.com.ph/stockMarket/companyInfoSecurityProfile.html?method=getListedRecords&common=yes&ajax=true";
var client = new RestClient();
client.BaseUrl = new Uri(url);
var request = new RestRequest();
IRestResponse response = client.Execute(request);
var strResult = response.Content;
return Ok("OK");
It takes so much time getting the response from the site. Maybe because of the source site behavior?
Thank you so much
I think it should be the response of your site.
Try testing another way around.
Maybe due to the slow response, your host prevent the request.

Authentication to REST API: digest type with cookie (c#)

I have a service REST API where I tryied to connect.
Using browser all is ok.
But in c# I always have an unauthorized answer.
I investigated this issue using fiddler and find out that in first unsuccessful reuest server returns some cookie, and browser use it in next session together with username/password (digest type).In this case second session is successful.
But when I try to send request using c# (I tried work with System.Net.WebClient and HttpWebRequest) I don't get response (I had timeout exception after some time).
My code:
WebClient webClient = new WebClient();
CredentialCache cache = new CredentialCache();
Uri prefix = new Uri(Url);
cache.Add(prefix, "Digest", new NetworkCredential(login, password));
webClient.Credentials = cache;
...
string response = webClient.DownloadString(restRequest);
Last line throws exception.
When I investigated this issue in Fiddler I found out that in first session with status 401 we recieved cookie (like on picture below).
fiddler's picture
Browser sends this cookie in next request and authentication happens successfully.
But in c# I couldn't geet this response with status 401. As I see in fiddler studio try to open new session 10-20 times during each next seconds before timeout exception will be thrown. And my response in null.
Also I have other environment without required cookie, there my code is working.
Please, give me a piece of advise hoe to get response with Status 401 and get cookie from it to set it to another request.
thanks
Mike
I resolved this issue using HttpWebRequest with defined empty (not null) CookieContainer.
My code:
HttpWebRequest request1;
HttpWebResponse response1 = null;
String responseBody;
request1 = (HttpWebRequest) WebRequest.Create(requestString);
request1.Credentials = cache;
request1.CookieContainer = new CookieContainer();
response1 = (HttpWebResponse) request1.GetResponse();
using (StreamReader stream = new StreamReader(response1.GetResponseStream(), Encoding.UTF8))
{
responseBody = stream.ReadToEnd();
}
In this implementation after first session with status 401 requests provide cookie from first session to next one and it returns with status code 200 OK.

Categories