Reputation: 1294
I am trying to detect incoming url in asp.net page and making some decision on the base of that url But I am facing some problem here is my c# code the detect the url and also condtions
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String url = Request.ServerVariables["HTTP_REFERER"];
if (url != "http://172.17.0.221:84/CP.aspx")
{
Response.Redirect("http://a.sml.com.pk");
}
else
{
Response.Redirect("http://172.17.0.221:85/MilkSale.aspx");
}
}
}
</script>
But When I call the page from http://172.17.0.221:84/CP.aspx then it gives this error:
This webpage has a redirect loop.
The webpage at http://172.17.0.221:85/MilkSale.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
Can any one tell me what may the error in this code?
Upvotes: 0
Views: 1291
Reputation: 91490
If your script statement is also on the MilkSale.aspx page, then it will fire every time the page is hit; in effect, it will redirect to itself forever (or, in this instance, until asp.net detects that it is requesting the same page over and over again).
To begin with:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String url = Request.ServerVariables["HTTP_REFERER"];
if(!String.IsNullOrEmpty(url))
{
if (!url.ToUpper().Contains("CP.ASPX"))
{
Response.Redirect("http://a.sml.com.pk");
}
else if (!url.ToUpper().Contains("MILKSALE.ASPX") && !url.ToUpper().Contains("CP.ASPX"))
{
Response.Redirect("http://172.17.0.221:85/MilkSale.aspx");
}
}
}
}
Then this will fix the first issue. However, you then have to consider some other issues with your code;
1) is pretty easy to use; you can use String.Compare(url, referrer, StringComparison.InvariantCultureIgnoreCase)
for example. In my code, I have used .ToUpper() but this is still fraught with issues (but makes for a compact example)
2) Is more difficult; you should really disassociate your redirect mechanism from the root url, or else you'll have to change your code everytime you change site. Either use the property HttpContext.Current.Request.Url.PathAndQuery
or, preferably, look at URL rewriting.
Upvotes: 2