HttpApplication and the current page - asp.net

As we all know the HttpApplication object holds objects regarding the requested page (HttpRequest) and the page where we are supposed to be redirected (HttpResponse); I need to get the url of the page which requested the page; how could I get it from the HttpApplication ?

You want to check the url referrer header like so:
string MyReferrer = Request.UrlReferrer.ToString();
This value is set by the browser however - so can't exactly be trusted from a security viewpoint.

You need to use the HttpRequest.UrlReferrer property see - http://msdn.microsoft.com/en-us/library/system.web.httprequest.urlreferrer.aspx

Related

what if in mvc3 localization and cookies get disabled

I have been working on mvc3 application and trying to localize the same. I came accross this very good site which made me use the logic of identifying the language selection by the user through cookies. What it does is:
User clicks the hyperlink of language
The clicked setting is saved in a cookie
Page is reloaded
In the BaseController class the ExecuteCore method is overloaded, here the cookie is read and the CurrentUICulture and CurrentCulture is set.
Now, this works great. But What if the user have disabled the cookie ?
So i feel this wont work.
Then I thot of using a workaround. What i tried was
I created a HiddenField
User clicks the hyperlink of language
The clicked setting is saved in a cookie
The clicked setting is also saved in HiddenField
Page is reloaded
In the BaseController class the ExecuteCore method is overloaded, here if the cookie value is present then its read and the CurrentUICulture and CurrentCulture is set.
If cookie is not found then I will try to read the hidden field value from Request object.
But I cant find the hiddenfield in the Request object in the ExecuteCore method.
So am i doing something wrong ?
PLease suggest me with some way. Also I dont want to use the route way of saving the culture.
Hidden fields values are only sent when you submit the form that contains them. If you only click on some hyperlink, the browser redirects to the href that this link is pointing to and no value will be sent, so you cannot expect to read it in your ExecureCore method. So, if you want this to work you will have to include the language as part of the querystring of the link.
Also I dont want to use the route way of saving the culture.
If you don't include the value as part of the url (query string or route), and cookies are disabled, the culture value has no way of reaching to your server.

How to find the url of parent page of a User control

I have a user control where if a certain action is performed I want to redirect to the page the user was on with some additional query string parameters.
So, if UserControl.ascx was on Home.aspx, I want to redirect to Home.aspx?action=true, and if UserControl.ascx was on Profile.aspx, I want to redirect to Profile.aspx?action=true
So basically, in my UserControl.ascx.cs I want to get the URL of the Parent Page. How can I get it?
You can look at the Request.Url, Request.RawUrl, Request.FilePath, and some of the other similar properties of the Request object - depending on how you're using this.
This will give you the requested URL from the browser, which will in turn tell you which page your control is living on.
You still have access to the request object from the user control, so do something like this:
string currentUrl = Request.Url.AbsoluteUri.ToString();
Request.UrlReferrer will get you the URL of the previous page... usually. There are some situations where it could be empty:
links clicked from an email message
shortcuts saved to a desktop
spoofed URLs
perhaps some settings or browsers
probably other scenarios as well
As long as your code "plays nicely" when UrlReferrer is empty or invalid, you should be good to go.
Request.Url.Scheme + "://" + Request.Url.Host + Request.RawUrl

Redirect to webapp default document when another page is specified?

IIS6, ASP.NET 2.0, No Forms Authentication
I'm calling Response.Redirect("~/foo.aspx"), but the default document ("Default.aspx") for my site is appearing. To make matters worse, it only happens intermittently. Sometimes the redirect displays the right page.
I've checked session state, and I don't see any values in the web.config (that is, I'm assuming I'm using the 20-minute defaults).
I wish I had more relevant information to share (I'll do my best to answer any questions).
Any ideas? Why isn't it redirecting to the specified page?
EDIT: I've looked deeeeeper into the code and learned more details.
Ok. There's foo.aspx and foo2.aspx (and the default document, Default.aspx). All pages extend from BasePage, which extends Page.
BasePage has a property named ReturnPage:
protected string ReturnPage {
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "";
}
return Session["ReturnPage"].ToString();
}
set { Session["ReturnPage"] = value; }
}
Users click on a LinkButton on foo.aspx, and the click event handler ends with two lines of code:
ReturnPage = ResolveUrl("~/foo.aspx");
Response.Redirect(ResolveUrl("~/foo2.aspx"));
The Page_Load of foo2.aspx has problems, and its error handling calls Response.Redirect(ReturnPage).
When I view the response headers of foo2.aspx, the 302 location is string.Empty (that is, there isn't one). That same response header has the same ASP.NET Session ID as the response of foo.aspx.
And remember -- this is intermittent. Sometimes, you can click on that LinkButton and go effortlessly to foo2.aspx, no problem. You can process the click with the exact same data once, and it will fail. You'll navigate from the default document (Default.aspx, where you were sent by the "bug") back to foo.aspx, click again with the same data (the same row in the grid/table -- the same LinkButton, essentially), and you'll be redirected to foo2.aspx without issue.
Placing a value in the session immediately before a Response.Redirect() is risky.
Changing foo.aspx's Response.Redirect() to the following might retain the session value more reliably:
Response.Redirect("~/foo2.aspx", false);
UPDATE: This ended up being fixed only by moving our session state into SQL Server. See related question: Why/when are session writes vulnerable to thread termination?
When you say:
Sometimes the redirect displays the right page.
Does it just happen, and you are not sure if there are certain pages that are affected by the problem? If this is the case, then you probably have a addressing problem. You can use either a relative path or an absolute path rather than an Application-relative path. I would also guess that you are trying to either direct to a page from a subdirectory on your site or to a subdirectory on your site. If you choose to stick with the Application-relative path make sure that are taking the subdirectory into account. (ex: ~/FooPages/Foo.aspx)
Here is a good reference page I just found:
http://nathanaeljones.com/129/types-of-asp-net-paths/
I'm a little confused here. What exactly are you trying to accomplish? You're getting the default document exactly because the 302 is blank. Your "inconsistent" behavior is almost certainly due to the way you are saving data in the Session.
The real issue here is why you're redirecting when foo2.aspx "has problems". What's the problem here? Why redirect? If you really need to redirect, why is the redirect target changed? Make it a static error reporting page and you'll be fine.
Once you redirect and get a new instance of the BasePage from foo2.aspx, won't that ReturnPage property be null again? Then once your page load errors out and tries to redirect it will be accessing a null string. Maybe try throwing that property in the Session
Session.Add("ReturnPage","~/foo.aspx")
instead of
ReturnPage = ResolveUrl("~/foo.aspx");
Ofcourse you would have to modify that error handling in the page load to grab it out of session rather than the property and you may have to rethink how the whole redirect is working in your system if this turns out to be the issue.
EDIT:
To test this idea about the property not getting set, or getting set correctly....(just to test I am not suggesting you should hard code the path in there), change your getter to the example below, then check to see if it works. Hope this helps, I am curious to find out what the problem is if this is not the issue.
get {
if (Session["ReturnPage"] == null) {
Session["ReturnPage"] = "~/foo.aspx";
}
return Session["ReturnPage"].ToString();
}

asp.net After a Server.Transfer how do you get the path of the current page?

To get the url of the current page, I usually do something like this:
string path = Request.Path;
If I do this after a Server.Transfer then I get the path of the page where the transfer was done. How can I get it for the current page?
For example:
On Page1.aspx I do Server.Transfer ("Page2.aspx")
On Page2.aspx Request.Path returns /Page1.aspx and not /Page2.aspx
I would like to get /Page2.aspx. How can I get it?
You're looking for the Request.CurrentExecutionFilePath property.
AppRelativeVirtualPath (http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.apprelativevirtualpath.aspx) seems to do the trick.
When you use Server.Transfer, despite the URL on browser doesn't change, the Request references URL does. So, you may use the UrlReferrer property's Request.
UrlReferrer gets information about the URL of the client's previous request that linked to the current URL.
For instance
string myContextBrowserPath = Context.Request.UrlReferrer.AbsolutePath

HttpContext.Current.User.Identity.Name is always string.Empty

Hi I use a custom MembershipProvider.
I want to know the current username during an application scenario, but when I try accessing HttpContext.Current.User.Identity.Name it always returns string.Empty.
if (Membership.ValidateUser(tbUsername.Text, tbPassword.Text))
{
FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
bool x = User.Identity.IsAuthenticated; //true
string y = User.Identity.Name; //""
FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, cbRememberMe.Checked);
}
Am I missing something?
FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
bool x = User.Identity.IsAuthenticated; //true
string y = User.Identity.Name; //""
The problem you have is at this point you're only setting the authentication cookie, the IPrincipal that gets created inside the forms authentication module will not happen until there is a new request - so at that point the HttpContext.User is in a weird state. Once the redirect happens then, because it's a new request from the browser the cookie will get read before your page is reached and the correct user object created.
Cookies are only set on the browser after a request is completed.
As an aside RedirectFromLoginPage creates a forms auth cookie anyway, you don't need to do it manually
Please try System.Web.HttpContext.Current.Request.LogonUserIdentity.Name instead of User.Identity.Name. It worked for me.
The value of HttpContext.Current.User.Identity.Name is set by the call to RedirectFromLoginPage. You can get the current user id from HttpContext.Current.User.Identity.Name once you are redirected to a new page. I'm not sure why you would need to access the user name through the User property in this context, couldn't you just use the value contained in tbUsername.Text?
in VS Community 2015 version, if you create a web forms application, it automatically add codes in web.config node to remove FormsAuthentication, try remove below section
<modules>
<remove name="FormsAuthentication"/>
</modules>
As already suggested FormsAuthentication.RedirectFromLoginPage() method, sets the Authentication Cookie automatically.
However in my case, i had nested web applications where i had cleared <httpModules> tag in child application (so that it does not inherit httpModules from its parent application) in the web.config file. Removing the unwanted parent httpModules made everything work again.
its better to check this tag before complicating things :)
If you're looking for the name of the user from the membership provider, try something like this ...
var user = Membership.GetUser( HttpContext.Current.User.Identity.Name );
If you're using URL rewrite or change your URL,it may be cause return Empty null value.You should try change path of your URL from .html to .aspx or none extendtion. this is issue for my case.You try.I hope this useful

Resources