Check a URL exists in ASP.NET with timeout - asp.net

I have 5 sites and a domain like x.company.com.
I want use x.company.com as a load balancer to send users to x1 .. x5 sub domains.
before send users to special sub domain I want check sub domain services is alive.
Now I do these but check of sub domain maybe too late to response, so I want
check sub domain service for 2 second and if no responses go to check another sub domain.
How to do that with c# asp.net?
or anybody have better suggestions for this balancing?

My code for check URL is:
private bool HttpExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
ServicePointManager.Expect100Continue = false;
request.Proxy = WebRequest.DefaultWebProxy;
request.Proxy = null;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}

Related

Using Web API redirect to angular html page

I want to redirect an HTML page using WEB API. I'm using ASP.Net Web API as a back-end and a front-end is on Angular 5. Here is my code. Here is my updated API source code.
[System.Web.Http.HttpGet]
public string[] Payment(string uri)
{
try
{
RegistrationRequestX reg = new RegistrationRequestX();
reg.Customer = "Test Api";
reg.Channel = Channels.Web;
reg.Language = "EN";
reg.Amount = 10;
reg.OrderID = "1234";
reg.OrderInfo = "test info";
reg.OrderName = "testing order";
string retPath = uri;
retPath = retPath.Replace("payment", "confirmation");
reg.ReturnPath = retPath;
RegistrationResponseX res = new RegistrationResponseX();
res = client.Register(reg);
client.Close();
string[] sess = new string[2];
sess[0] = paymentPortalURL;
sess[1] = transactionID;
return sess;
}
catch (Exception)
{
throw;
}
}
You can return the redirect uri back to angular client with status code 302.
At angular, you should check the returned status code. If it is 302 then redirect to returned redirect url.
Use the window.location.href in your angular to set the first element of the array that you return to redirect to the Url that you expected
You can change a return type of the cotroller method on IHttpActionResult and return using Ok and Redirect methods, inherited from ApiController.
For example see code below if you want to either return string[] with ok code (200) or a redirect (302) with Location response header with provided redirect link, depending on some condition:
[System.Web.Http.HttpGet]
public IHttpActionResult Payment(string uri)
{
string[] sess = ...
if (someRedirectCondition)
return Redirect("http://a.link.to.your.html.page");
else
return Ok(sess); // A method type is inferred to Ok<string[]>(string[] content)
}

Forwarding SAML by delegation - POST from web server to web server

I have an ASP.NET web app using WSFederation for user authentication. I would like to impersonate the users and make a webrequest to another web server from my web server through delegation. The other server also does WSFederation.
Ultimately, i just need a single page from the other web server. There is some header info i need from that HTTP Response Header. Sample code below.
I have been following these steps but this is for Webserver -> WCF, not Webserver -> Webserver.
https://technet.microsoft.com/en-us/library/adfs2-identity-delegation-step-by-step-guide(v=ws.10).aspx
Based on that article, I got the following in my web.config:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
Here is a bit of sample code that I'm running to make the web request to the second webapp. Its a simple POST and I need to read some data off the Response header.
try
{
var claimsPrincipal = ClaimsPrincipal.Current;
if (claimsPrincipal.Identities.First().BootstrapContext == null)
{
throw new Exception("No bootstrap context found");
}
WebRequest request = WebRequest.Create("https://destServer/sap/bc/gui/sap/its/webgui/?sap-client=555&sap-language=en");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseBody = new StreamReader(response.GetResponseStream()).ReadToEnd();
var responseHeaders = "";
for (int i = 0; i < response.Headers.Count; ++i)
{
responseHeaders += response.Headers.Keys[i] + ": " + response.Headers[i] + " <br/>";
}
ViewBag.responseHeader = responseHeaders;
ViewBag.responseBody = responseBody;
}
catch (Exception e)
{
ViewBag.responseHeader = "FAILED";
ViewBag.responseBody = e.Message;
}
I'm not sure how I need to add the appropriate SAML token into the request. Right now this results in a redirect response to the STS. I know I need to work with the STS admins to get the correct tokens, but assuming I already had this, how does one POST (or GET) to another website with those SAML tokens?

check URL exists or throws page not found message in asp.net

I want to validate an url, whether it exists or throwing page not found error. can anyone help me how to do it in asp.net.
for e.g., my url may be like http://www.stackoverflow.com or www.google.com i.e., it may contain http:// or may not. when i check, it should return the webpage valid if exists or page not found if doesnot exists
i tried HttpWebRequest method but it needs "http://" in the url.
thanks in advance.
protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
Try this
using System.Net;
////// Checks the file exists or not.
bool FileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if it Exist
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false. So the URL is Not Exist
return false;
}
}
Hope I Helped

ASP.net: Getting HTTPS data server-side?

I previously asked on StackOverflow how to parse XML downloaded programmatically by my ASP.net application. By this, I mean that the user visits https://www.example.com/page1.aspx. The code-behind for page1.aspx is supposed to somehow download and parse an xml file located at https://www.example.com/foo.xml.
I received good answers about how to parse the XML. However, I've been out of luck with being able to retrieve XML from my secure HTTPS server.
I am looking at a situation where https://www.example.com/foo.xml authenticates requests with a cookie. (third party system, not Forms Authentication). The answer I received to my question about how to download and parse XML suggested that I use the System.Net.WebClient class. I read that the WebClient class must be customized to work with cookies. Therefore, I wrote the following code:
public class WebClientWithCookies : WebClient
{
private CookieContainer m_container = new CookieContainer();
public CookieContainer CookieContainer
{
get { return m_container; }
set { m_container = value; }
}
public void addCookie(Cookie cookie)
{
m_container.Add(cookie);
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if ( request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
} // end class
However, when the request is received at https://www.example.com/foo.xml, there are no cookies in the request, and so it doesn't work.
How can I work around this problem?
Where are you creating the cookie? That seems to be a missing part from the code you are displaying. There is an "HttpCookie" class as part of the System.Web name space that may be useful.
Here's the code that I eventually wrote that solved the problem:
private XmlDocument getXmlData(string url)
{
System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.CookieContainer container = new System.Net.CookieContainer();
for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count; i++)
{
System.Web.HttpCookie httpcookie = System.Web.HttpContext.Current.Request.Cookies[i];
string name = httpcookie.Name;
string value = httpcookie.Value;
string path = httpcookie.Path;
string domain = "my.domain";
System.Net.Cookie cookie = new System.Net.Cookie(name, value, path, domain);
container.Add(cookie);
}
rq.CookieContainer = container;
rq.Timeout = 10000;
rq.UserAgent = "Asset Tracker Server Side Code";
System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)rq.GetResponse();
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream());
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.Load(rs.GetResponseStream());
return xml;
}

Google Checkout HTTP Post with ASP.net

I have 2 pages I created in ASP.net(C#). The first one(called shoppingcart.asp) has a buy it now button. The second one(called processpay.asp) just waits for google checkout to send an HTTP request to it to process the payment. What I would like to do send a post statement to google checkout with a couple of variables that I want passed back to processpay.asp(ie clientid=3&itemid=10), but I don't know how to format the POST HTTP statement or what settings I have to change in google checkout to make it work.
Any ideas would be greatly appreciated.
Google Checkout has sample code and a tutorial on how to integrate it with any .NET application:
Google Checkout API - Google Checkout Sample Code for .NET
Make sure to check the section titled: "Integrating the Sample Code into your Web Application".
However, if you prefer to use a server-side POST, you may want to check the following method which submits an HTTP post and returns the response as a string:
using System.Net;
string HttpPost (string parameters)
{
WebRequest webRequest = WebRequest.Create("http://checkout.google.com/buttons/checkout.gif?merchant_id=1234567890");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException e)
{
// handle e.Message
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
// get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{
return null;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException e)
{
// handle e.Message
}
return null;
}
Parameters need to be passed in the form: name1=value1&name2=value2
The code will likely end up looking something like this:
GCheckout.Checkout.CheckoutShoppingCartRequest oneCheckoutShoppingCartRequest =
GCheckoutButton1.CreateRequest();
oneCheckoutShoppingCartRequest.MerchantPrivateData = "clientid=3";
GCheckout.Checkout.ShoppingCartItem oneShoppingCartItem =
new GCheckout.Checkout.ShoppingCartItem();
oneShoppingCartItem.Name = "YourProductDisplayName";
oneShoppingCartItem.MerchantItemID = "10";
oneCheckoutShoppingCartRequest.AddItem(oneShoppingCartItem);
Yesterday I used http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx to send the post data and it works fine

Resources