Getting the referrer's web server name - c#

I am placing a JS file to remote server(s). I d like to know where the request is coming from.
ie : i have a js on google.com and upon user click on the link that s produced by js, it triggers some c# code on my server, but i also have the same js on yahoo.com and i d like to be able to know where the request is coming from.
How to find this ?

System.Environment.MachineName should contain the name of the server.

In ASP.NET, the referring page is given by Request.UrlReferrer as a Uri object.
This is also available as Request.ServerVariables["HTTP_REFERER"] as a string.

Request.ServerVariables["SERVER_NAME"]
Also you may need:
Request.ServerVariables["SERVER_PORT"]

Following on your own lead for "System.Web.HttpContext.Current.Request.ServerVariables", the MSDN documentation for the ServerVariables property contains some sample code on how to retrieve all available named server variables:
int loop1, loop2;
NameValueCollection coll;
// Load ServerVariable collection into NameValueCollection object.
coll=Request.ServerVariables;
// Get names of all keys into a string array.
String[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("Key: " + arr1[loop1] + "<br>");
String[] arr2=coll.GetValues(arr1[loop1]);
for (loop2 = 0; loop2 < arr2.Length; loop2++) {
Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
}
}
Furthermore, it also contains a link to all server variables supported by IIS
IIS Server Variables
For example, the "REMOTE_HOST" variable will give you:
The name of the host that is making the request. If the server does not have this information, it will set REMOTE_ADDR and leave this empty.

Related

ASP.net not catching QueryString

I have created a ASP.net application,where i change the language base on its query string.
I have two servers both are https ,but one is redirected by netscaler
https://testMyLiveCode.com
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/?
For eg
https://testMyLiveCode.com/?ln=en
This is my asp.net code
string strNewLanguage = Request.QueryString["ln"].ToLower();
SessionHelper.Language = strNewLanguage ;
string strNewURL = Request.RawUrl.ToLower().Replace("ln=" + Request.QueryString["ln"], "");
Response.Redirect(strNewURL);
What i actually do is that change the language depending on querystring and change the querystring and redirects
THis works perfectly with my https Server
https://testMyLiveCode.com/?ln=en
But this doesnt work with my netscaler url
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/?
This is my url
And after i added the querystring to it,it does not work
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/??ln=en
Can anyone help why this is not working as the url already has a ? in it???
Thanks for any help
My suggestion is to change the string which contains '?', it you can't then below instruction and code might help you
I am writing below code based on language array, you need to modify this based on your requirement, Hopefully this will help.It's bad code you have to modify this to make this good
string[] obj = new string[5] {"hi","en","ar","or","xy" };
string urlString = Request.RawUrl.ToLower();
int location = 0;
for (int i = 0; i < obj.Length; i++)
{
if (urlString.Contains("=" + obj[i]))
{
location = i;
break;
}
}
string strNewURL = Request.RawUrl.ToLower().Replace("ln=" + obj[location], "");
Response.Redirect(strNewURL);

PayPal RestApi Identity Service For Asp.net C# Not Returning correct url

I am currently trying to implement PayPal login on our clients site to be able to integrate seamless checkout. I have a link to the documentation on how to do it here:
https://devtools-paypal.com/guide/openid
After implementing this I noticed that even if I pass in the mode as sandbox, it still gives me a live url. Also, the client id comes back empty (I'm guessing b/c the client id I'm using is only for testing).
How can I force the api to return a sandbox/testing url?
just create simple example,like take one button on the form and in code behind file put
following code in the button click event:
string business = "here type your email id";
string itemName = "Plan1"; //this variable for itemname.
double itemAmount = 8.00;// this variable for itemprice.
string currencyCode = "USD"; //this variable for currency code.
StringBuilder ppHref = new StringBuilder();
ppHref.Append("https://www.paypal.com/cgi-bin/webscr?cmd=_xclick");
ppHref.Append("&business=" + business);
ppHref.Append("&item_name=" + itemName);
ppHref.Append("&amount=" + itemAmount.ToString("#.00"));
ppHref.Append("&currency_code=" + currencyCode);
Response.Redirect(ppHref.ToString(), true);

How to Get the HTTP Post data in C#?

I am using Mailgun API. There is a section that I need to provide a URL to them, then they are going to HTTP Post some data to me.
I provide this URL (http://test.com/MailGun/Webhook.aspx) to Mailgun, so they can Post data. I have a list of parameter names that they are sending like (recipient,domain, ip,...).
I am not sure how get that posted data in my page.
In Webhook.aspx page I tried some code as follows but all of them are empty.
lblrecipient.text= Request.Form["recipient"];
lblip.Text= Request.Params["ip"];
lbldomain.Text = Request.QueryString["domain"];
Not sure what to try to get the posted data?
This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
This code reads the raw input stream from the HTTP request. Use this if the data isn't available in Request.Form or other model bindings or if you need access to the bytes/text as it comes.
using(var reader = new StreamReader(Request.InputStream))
content = reader.ReadToEnd();
You can simply use Request["recipient"] to "read the HTTP values sent by a client during a Web request"
To access data from the QueryString, Form, Cookies, or ServerVariables
collections, you can write Request["key"]
Source:
MSDN
Update: Summarizing conversation
In order to view the values that MailGun is posting to your site you will need to read them from the web request that MailGun is making, record them somewhere and then display them on your page.
You should have one endpoint where MailGun will send the POST values to and another page that you use to view the recorded values.
It appears that right now you have one page. So when you view this page, and you read the Request values, you are reading the values from YOUR request, not MailGun.
You are missing a step. You need to log / store the values on your server (mailgun is a client). Then you need to retrieve those values on your server (your pc with your web browser will be a client). These will be two totally different aspx files (or the same one with different parameters).
aspx page 1 (the one that mailgun has):
var val = Request.Form["recipient"];
var file = new File(filename);
file.write(val);
close(file);
aspx page 2:
var contents = "";
if (File.exists(filename))
var file = File.open(filename);
contents = file.readtoend();
file.close()
Request.write(contents);
Use this:
public void ShowAllPostBackData()
{
if (IsPostBack)
{
string[] keys = Request.Form.AllKeys;
Literal ctlAllPostbackData = new Literal();
ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
for (int i = 0; i < keys.Length; i++)
{
ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
}
ctlAllPostbackData.Text += "</div>";
this.Controls.Add(ctlAllPostbackData);
}
}
In the web browser, open up developer console (F12 in Chrome and IE), then open network tab and watch the request and response data. Another option - use Fiddler (http://fiddler2.com/).
When you get to see the POST request as it is being sent to your page, look into query string and headers. You will see whether your data comes in query string or as form - or maybe it is not being sent to your page at all.
UPDATE: sorry, had to look at MailGun APIs first, they do not go through your browser, requests come directly from their server. You'll have to debug and examine all members of Request.Params when you get the POST from MailGun.
Try this
string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++)
{
// here you get the name eg test[0].quantity
// keys[i];
// to get the value you use
value = Request.Form[keys[i]];
}
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);
You can try to check the 'Request.Form.Keys'. If it will not works well, you can use 'request.inputStream' to get the soap string which will tell you all the request keys.

Navigating to DNN Module

I'm forming a newsletter with links to various html modules within my DNN website. I have access to each of their ModuleID's and I'm wanting to use that to get the url. The current approach (made by a third party developer) worked, but only to a degree. The url's are incorrectly formed when the Modules are located deeper in the website.
For example module located at www.website.com/website/articles.aspx is works fine, but a module located www.website.com/website/articles/subarticles.aspx won't. I know this is because the url is incorrectly formed.
Here's the current code:
DotNetNuke.Entities.Modules.ModuleController objModCtrlg = new DotNetNuke.Entities.Modules.ModuleController();
DotNetNuke.Entities.Modules.ModuleInfo dgfdgdg = objModCtrlg.GetModule(ContentMID);
TabController objtabctrll = new TabController();
TabInfo objtabinfoo = objtabctrll.GetTab(tabidfrcontent);
string tabnamefremail= objtabinfoo.TabName;
moduletitlefrEmail = dgfdgdg.ModuleTitle;
string readmorelinkpath = basePath + "/" + tabnamefremail + ".aspx";
ContentMID is the current module ID I'm looking at. I've tried to use Globals.NavigateURL, but that always crashes with Object reference not set to an instance of an object. error. Same thing when I use objtabinfoo.FullUrl so I'm currently at a loss as to how I get the specific modules URL.
EDIT: Here's some more code as to how the tabId is retrieved.
IDictionary<int, TabInfo> dicTabInfo12 = new Dictionary<int, TabInfo>();
ContentMID = Convert.ToInt32(dsNewsList.Tables[0].Rows[i]["ModuleID"]);
dicTabInfo12 = objTabctrl.GetTabsByModuleID(ContentMID);
if (dicTabInfo12.Count > 0)
{
string tester = ""; //Debug
foreach (KeyValuePair<int, TabInfo> item1 in dicTabInfo12)
{
tabidfrcontent = item1.Key;
}
}
You really should be using NavigateUrl to build the links ance if you have the tabid, you are golden.
string readMoreLinkPath = NavigateUrl(tabidfrcontent);
Nice and simple
Okay, colleague suggested this and it works great within a scheduler.
string linkPath = basePath + "/Default.aspx?TabID=" + tabID;
Will Navigate you to the correct tab ID. So this would be the best solution if you're forced to work within a scheduler where you can't use NavigateUrl without some major workarounds.

How can I get the baseurl of site?

I want to write a little helper method which returns the base URL of the site. This is what I came up with:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}
Is there any mistake in this, that you can think of? Can anyone improve upon this?
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
That's it ;)
The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:
uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
I believe that the answers above doesn't consider when the site is not in the root of the website.
This is a for WebApi controller:
string baseUrl = (Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/')
+ HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;
To me, #warlock's looks like the best answer here so far, but I've always used this in the past;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Or in a WebAPI controller;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and #warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)
String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority)
+ Configuration.VirtualPathRoot;
I'm using following code from Application_Start
String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
Request.Url.OriginalString: return the complete path same as browser showing.
Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.
So if you want to access your domain name do consider to include the application name in case of:
IIS deployment
If your application deployed on the sub-domain.
====================================
For the dev.x.us/web
it return this
strong text
Please use the below code                           
string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);
you could possibly add in the port for non port 80/SSL?
something like:
if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
{
port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
}
and use that in the final result?

Categories