i am trying to remove default.aspx from any request that might have it.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string url = context.Request.Url.ToString();
// remove default.aspx
if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
url = url.Substring(0, url.Length - 12);
context.Response.Redirect(url);
}
}
gives an error:
**too many redirects occurred trying to open...**
what can i change to make it work?
thnx
k got it.
instead of using:
string url = context.Request.Url.ToString();
i tried:
string url = context.Request.RawUrl.ToString();
and that WORKS! together with what you guys said :)
I think that if you put the redirect inside the if you don't have to deal with infinite redirects.
You are endlessly redirecting.
Each time the following line executes the Application_BeginRequest event is fired again.
context.Response.Redirect(url);
Put the redirect inside the if statement like this.
if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
url = url.Substring(0, url.Length - 12);
context.Response.Redirect(url);
}
Related
I'm looking for a way to end my session and redirect the user to the login screen when my system gives TimeOut.
I tried to use Session.Abandon () according to some examples that I researched. But I do not know what I'm doing wrong. below is my code to do in Global.asax:
protected void Application_EndRequest(object sender, EventArgs e)
{
var context = new HttpContextWrapper(Context);
if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
var redirectLocation = context.Response.RedirectLocation.ToString();
context.Response.RedirectLocation = null;
context.Response.ContentType = "text/plain";
context.Response.Write("session_timeout;" + redirectLocation);
Session.Abandon();
Response.Redirect("~/Account/Login");
}
}
The code runs only until: context.Session.Abandon (); and does not redirect to the login screen unless I refresh the page.
public ActionResult LogOff()
{
HttpContext.Session.Remove(SessionKeys.UserType);//This will remove all keys from session variable. For example, if your session contains id, name, phone number, email etc.
HttpContext.Session.RemoveAll();//This will remove all session from application
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
I was able to resolve my question this way:
1 - I set a timeout time in my Web.config by adding this tag:
<sessionState timeout="16"></sessionState>
2 - I created a function in javascript that veridifca if the timeout time came to an end:
var sessionTimeoutWarning = #Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
alert("Your session has expired");
window.location = "/Account/SessionTimeOutLogOff";
}
Note: This function was put in my _Layout.chshtml
I have a page that if you don't have the cookie i want it redirects you to the page the cookie is created. Basically if you didn't tell me you are old enough you gotta redirect to a page and give me your age. Long story short if i get redirected to this page where i am asking for you age and the end user doesn't decide to give me there age and click on that same page or another page. My code is adding onto the existing string.
protected void Page_Load(object sender, EventArgs e)
{
string referrer = Request.UrlReferrer.ToString();
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + referrer);
}
if I call this page to load multiple times my URLS can get really ugly.
http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/
it is like it is concatenating onto the existing. Is there a way for me to prevent this?
I basically want to have it so that i only have 1 param in my ReturnUrl QueryString and so that it won't duplicated if that already has a value.
You can do this by using the Uri class to obtain only the parts of the referrer without the query string. For example:
if (Request.Cookies["Age"] == null)
{
string referrer = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
Response.Redirect(referrer);
}
For more information on GetLeftPath, see: http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx
Here is the code that fixed the problem. Don't know why my last answer was deleted.
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + url);
Is it possible to get the URL of the next page when leaving the current page in C#?
On my current page I would like to capture the url of the next page before the next page loads. I'm not sure where to start for this...or in which method on my page I would place this logic (such as page_load, buttonClick etc.)
I don't think that it's possible to "capture the url of the next page", but you can get the current request as soon as possible. Use Global.asax therefore:
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = base.Context;
HttpResponse response = context.Response;
HttpRequest request = context.Request;
var url = request.RawUrl;
// and many other properties ...
}
}
Assuming you're doing paging through query strings and your current page is:
url.com/default.aspx?page=1
Then getting the next page URL would just be incrementing the page query string, so:
if (!String.IsNullOrempty(Request.QueryString["page"]) {
int nextPageNumber = int.Parse(Request.QueryString["page"] + 1;
string nextPageUrl = String.Format("url.com/default.aspx?page={0}, nextPageNumber);
}
Ideally you would use UriBuilder to reconstruct the domain and not hard code it as I have in the String.Format method. I did this just for brevity.
CodeProject has a project for saving change on close or exiting page which might be helpful to you.
All the users on my site have public-facing profile pages. I am using URL rewriting to change urls from the form http://mysite.com/profile.aspx?id=sdsdfsdsdfsdfdsdffsdfsdf into http://mysite.com/Username like this (in my global.asax file):
static Regex _handleRegex1 = new Regex("/(?<hndl>[\\w]+)/?$", RegexOptions.Compiled);
void Application_BeginRequest(object sender, EventArgs e)
{
System.Text.RegularExpressions.Match handleMatch = _handleRegex1.Match(Request.Url.LocalPath);
if(handleMatch.Success){
String handle = handleMatch.Groups[1].Value;
using (SqlQuery query = new SqlQuery("[dbo].[sp_getUserIdByHandle]"))
{
try
{
query.AddParameter("#handle", handle, System.Data.SqlDbType.NVarChar, false);
query.AddParameter("#userId", new Guid(), System.Data.SqlDbType.UniqueIdentifier, true);
query.ExecuteNonQuery();
Object userId = query.GetOutParameter("#userId");
if (userId == DBNull.Value)
{
Response.Redirect("~/default.aspx");
}
else
{
Context.RewritePath(string.Format("~/profile.aspx?id={0}&{1}", userId, Request.QueryString));
}
}
catch (Exception ex)
{
}
}
}
}
This works fine. However, if I do a postback to the server, the URL changes from something like /username to the form /profile?id=5ab47aa3-3b4d-4de6-85df-67527c9cdb52&, which I want to hide from the user.
I thought about doing something like Response.Redirect(Request.RawUrl); to sent the user back to the right page. However, Request doesn't seem to contain any information about the desired URL.
Is there any way to find the pre-rewritten URL?
What platform are you on? If IIS 7 you would be best off using IIS URL Rewrite 2.0. You can find some suggestions on dealing with postback using this.
I suggest you use Routing, that way you can write your code the ASP.NET way but still have the Urls you want:
Routing with ASP.NET Web Forms
I put the authentication attribute that sets:
filterContext.Result = new HttpUnauthorizedResult();
so when I try to access
http://www.mysite.com/Forum/Polls
and I am not authenticated I am redirected to:
http://www.mysite.com/Account/Log?ReturnUrl=%2FForum%2FPolls
I want to have the following line instead:
http://www.mysite.com/Account/Log?back=%2FForum%2FPolls
, so instead of 'ReturnUrl' need 'back'. Where I can ovveride this behaviour. Thanks.
You can rewrite "ReturnURL" on EndRequest event.
This is sample code.
protected void Application_EndRequest()
{
if (Response.StatusCode != 301 && Response.StatusCode != 302) return;
var targetUrl = Response.RedirectLocation.Replace("ReturnUrl","back");
Response.RedirectLocation = targetUrl;
}
Hope this code.
It doesn't look like you can. That comes from System.Web.Security.FormsAuthentication.GetLoginPage()
If you look at the code, you see that it is indeed a hard coded literal. At least in System.Web version 2.0.0.0