Cant HttpWebRequest in Azure via Hangfire - c#

I have a code that run a hangfire background job. Now the job calls a class that in turn this class function will perform a HttpWebRequest to my own UmbracoApiController. Now it's working in my local but somehow when I trigger my hangfire in Azure I'm getting an error
Correct me if I'm wrong but somehow I think Azure does not allow performing a HttpWebRequest in the background job like Hangfire? or am I just missing a configuration to allow this action? if so where can I find this settings that will allow my jobs to perform HttpWebRequest?
Below is my code that calls my API within the same apps and domain
public string TestApi()
{
WebRequest request = WebRequest.Create(ConfigurationManager.AppSettings["Background:Test"]);
// If required by the server, set the credentials.
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
return "Yes " + response;
}

Related

C# calling a webservice result in 401

I'm trying to call a simple web service to get long and lat of an address, which works when I try it manually :
https://services.gisgraphy.com/geocoding/?address=paris
But with the code, I get 401 unauthorize.. What am I doing wrong ?
WebRequest request = WebRequest.Create("https://services.gisgraphy.com/geocoding/?address=paris");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";
WebResponse response = request.GetResponse(); // It happens here.
What am I doing wrong?
You haven't read the big blue bar on top of the website belonging to the API you're calling:
Gisgraphy is open sources and only use open data. This server is for demonstration only. Test it, Play with webservices but then Install Gisgraphy locally or subscribe to premium hosted services
So they're probably detecting that you're calling their API from outside their playground, and are denying you to do so.
So, either install it locally, or subscribe to their hosted services. The latter probably gives you an API key that allows you to make API calls.
Of course you can fake your way around this by imitating that your request comes from a browser, for example with User-agent and Accept headers, but surely they'll try and detect this and block your IP address entirely. Just pay up, or host it locally.
Few things on this question :
Check if the URL/web-service is directly accessible via
browser/postman tool.
Secondly , as one of my fellow friend there mentioned this
web-service has some security protocol. May be its not allowing
requests from outside (i.e. other than its domain to come in)
Once you drill down the above two possibility ,you should be in a good shape to move ahead.

WebException SecureChannelFailure when invoking web service over https from Xamarin Droid app

I'm creating a Xamarin.Droid app with Visual Studio (C#).
I have a RESTful web service (WebAPI) from which I want to retrieve some data in a Xamarin Droid project, using HttpWebRequest. The fact that it's WebAPI and HttpWebRequest is not the key as I had the exact same problem (described below) with some older WSE 3.0 web services and the use of HttpClient in the generated proxies. In the case of those WSE 3.0 web services we solved the problem by extending the generated proxy class to use ModernHttpClient instead. We didn't realize this problem manifests outside of HttpClient. I now think we must be doing something wrong, as opposed to blaming HttpClient.
In the current iteration, connecting to WebAPI, I'm using HttpWebRequest. Whether using HttpWebRequest or HttpClient, everything works fine as long as I'm connecting via http. As soon as I try to connect via https the request fails. For clarification, the web server hosting the web service does have a valid certificate (it's not expired, and has a valid CA.)
I have not been able to find any solution to this problem, despite a ton of Googling. I can barely find references to other people having this problem, much less a solution, which makes me think there must be something wrong in what I'm doing.
Basically, you can this method to a Xamarin.Forms Droid project and call it. If url is using https then request.GetResponse() throws a WebException: "Error: SecureChannelFailure (The authentication or decryption has failed.)". If url is using plain http then the call executes cleanly and returns the expected data.
using System;
using System.IO;
using System.Net;
using Android.App;
using Android.Content.PM;
using Android.OS;
// ...
private string FetchData()
{
// Public test server that's handy for testing JSON code.
// http://jsonplaceholder.typicode.com
string url = "https://jsonplaceholder.typicode.com/posts/1";
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 10 * 1000; // 10 seconds
request.Accept = "application/json";
request.Method = "GET";
string result = "";
try
{
using (WebResponse response = request.GetResponse())
{
result = "Presumably, do something with response.GetResponseStream()";
}
}
catch (Exception ex)
{
result = $"{ex.GetType().Name}: {ex.Message}";
}
return result;
}
The basic pattern there comes from a Xamarin "recipe": Call a REST Web Service. I changed it to be synchronous because when I change request.GetResponse() to request.GetResponseAsync() (and async-await) then the call either times out, or hangs indefinitely, obfuscating the underlying WebException (SecureChannelFailure).
This is a simple HTTP GET, and any browser, or REST/SOAP utility (e.g. "Simple REST Client" for Chrome) can be used to build and send that exact same request, and it works fine with both http and https. Similarly, I can take that code above and paste it into a Windows Console application and it works fine with both http and https.
For the record, love it or hate it, I have also tried adding a delegate of { return true; } to the System.Net.ServicePoint.ServerCertificateAuthenticationCallback event. To me that wouldn't be a solution anyway, but it might help diagnose the problem. Too bad a breakpoint set in that delegate is never tripped, indicating my code never even gets to that point.
It seems impossible to me that invoking web services through https is not supported in a Xamarin Droid app, so I'm going on the assumption that I'm doing something wrong. What could be causing this failure in Xamarin Droid, when it works fine in a browser, and in a plain Windows Console app?
if you call a HTTP url and get this exception , be sure set redirect to false:
request.AllowAutoRedirect = false;
if you call a HTTPS url then put these lines before your request code:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Timeout exception in Web Service

I have written a program in c# windows application that calls a web service by creating HttpRequest object and gets the response. Everything was working fine as expected in the development phase but now in User Acceptance Testing, whenever the web service is called it is throwing a timeout exception as I am not getting a response after invoking the web service url. But if I invoke the same url from Fiddler, I am getting an immediate response with 200 status code. Below is the code snippet of my program calling a web service url
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stWebServiceURI);
request.Method = "GET";
request.ContentType = "text/xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
NOTE: A web service call from my application is not getting logged in Fiddler.
Any help on this is much appreciated. Thanks in Advance

How to forward a REST web service using C# (WCF)?

There is a web service that can only be consumed via http and a client that can only consume https web services. Therefore I need some intermediary that forwards on requests received in https and returns responses in http.
Supposing that the intermediary is completely dumb save for the fact that it knows where the web service endpoint is (i.e. it doesn't know what the signature of the service is, it just knows that it can communicate with it via an http web request, and it listens on some https uri, forwarding on anything it receives), what is the most simple way of achieving this?
I've been playing around with this all day and am not sure how to achieve the "dumb" bit, i.e. not knowing the signature for passing back the verbatim response.
A dumb intermediary is essentially a proxy. Your best bet might to be just use standard asp.net pages (instead of shoehorning into service functionality like ASMX or WCF which are just going to fight you) so you can receive the request exactly as-is and process it in a simple way using standard request/response. You can make use of HttpWebRequest class to forward the request on to the other endpoint.
Client requests https://myserver.com/forwarder.aspx?forwardUrl=http://3rdparty.com/api/login
myserver.com (your proxy) reads querystring forwardUrl and any POST or GET request included.
myserver.com requests to http://3rdparty.com/api/login and passes along GET or POST data sent from the client.
myserver.com takes response and sends back as response to other endpoint (essentially just Response.Write contents out to the response)
You would need to write forwarder.aspx to process the requests. Code for forwarder.aspx would be something like this (untested):
protected void Page_Load(object sender, EventArgs e)
{
var forwardUrl = Request.QueryString["forwardUrl"];
var post = new StreamReader(Request.InputStream).ReadToEnd();
var req = (HttpWebRequest) HttpWebRequest.Create(forwardUrl);
new StreamWriter(req.GetRequestStream()).Write(post);
var resp = (HttpWebResponse)req.GetResponse();
var result = new StreamReader(resp.GetResponseStream).ReadToEnd();
Response.Write(result); // send result back to caller
}

HTTP Requests (POST) doesn't works correctly in a DLL Library?

I'm trying to use TweetSharp in a DLL Library.
When I execute the following code in a DLL Library, the response returns invalid (417 Unknown):
var verify = FluentTwitter.CreateRequest()
.AuthenticateWith("<HIDDEN>",
"<HIDDEN>",
"<HIDDEN>",
"<HIDDEN>")
.Statuses().Update("It works!");
var response = verify.Request();
When I execute the same code in a Windows Application, the response returns correctly.
Is there any thing (configuration) that could process HTTP Requests (using POST) differently using the same code in DLL Library and Windows Application?
most likely, the library has the "Expect100Continue" set to true. It should be set to false.
http://groups.google.com/group/twitter-api-announce/browse_thread/thread/7be3b64970874fdd
Looks as though this library needs to be updated. This was changed about 10 months ago.
So the code should something like this...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newURL);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
TweetSharp definitely handles the Expect100Continue issue, so something else is at play here. What does your policy file look like? You need to make sure you can send HTTP requests from DLLs if you're in a medium trust environment by modifying your policy.
Probably its current logged user related
Try to log with your website application pool user and run your code again

Categories

Resources