How to deny direct access to page - c#

how can I deny direct access (by typing the full url) to pages in asp.net, without using roles in web.config something simle.
I've used :
if (Session.IsNewSession)
Response.Redirect("Default.aspx");
the problem with it is in the first time everything is ok and the redirect is working, but if I open a new tab in the same browser and enter the url again it fails.
How can it be solved?
thanx

Try this:
Page 1
Context.Items.Add("somevar","someval");
Page 2
if ( Context.Items["somevar"] == null )
{
// the page is not redirected from Page 1
}

Using session you can solve this issue.
Build an HttpModule and in context_BeginRequest you can get the current URL . Later conditionally redirect to the default page.
public class RedirectionModule : IHttpModule
{
void context_BeginRequest(object sender, EventArgs e)
{
//this user already already eligible to go inside page ?
if (Session["eligible-to-go-inside"] == null)
{
//new user
//check current request url is default.aspx
//if not forward to default page
}
}
}
in default.aspx page if the user full fill the requirement to go to inner page (like logged in) then set
Session["eligible-to-go-inside"] = "yes";

Related

ASP.Net on start runs wrong page as Sartup Page

I have a simple folder structure for my multilingual website on localhost
Default.aspx
images
css
js
en/Default.aspx
en/ContactUs.aspx
....
ar/Default.aspx
ar/xxxxx.aspx
Problem i am facing is very strange to me. i have a simple code to check the browser language set by user and accordingly i redirect user to English or Arabic version of website.
Irrecpective of what code i wring it always redirects me to English version of website and executes the en/Default.aspx page
Even commenting all the code in Default.aspx page it still redirect it to the en/Default.aspx page. while it should not do any thing.
I have set Default.aspx as Set As Default Page but it doesn't make any difference. I removed even global.asa that had routing code, i also removed all the compiler code related to this website on local host but it still keeps doing the same thing.
I have checked web.config file there is nothing wrong with that.
Even after removing the Default.aspx page it sill redirects me to en/Default.aspx i am frustrated with this problem.
I am not sure what is wrong. I re-started system with no result.
I am using visual studio 2010 for asp.net web form project.
http://localhost:49831/AlShindagah/
ALWAYS take me to below URL
http://localhost:49831/AlShindagah/en/Default.aspx
CODE of Default.aspx before i deleted it
public partial class DefaultMain : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//switch (Session["lang"].ToString().ToLower())
//{
// case "en-us":
// Response.RedirectPermanent("~/en/Default.aspx");
// break;
// case "ar-ae":
// Response.RedirectPermanent("~/ar/Default.aspx");
// break;
// default:
// Response.RedirectPermanent("~/en/Default.aspx");
// break;
//}
}
//// Localization and Globalization code
//protected override void InitializeCulture()
//{
// String lang = Request["Language"];
// Session["lang"] = Helper.DetectLanguage(lang);
// //Set Direction of page LTR/RTL
// if (Session["lang"] == "ar-AE")
// {
// Session["PageDIR"] = "rtl";
// }
// else
// {
// Session["PageDIR"] = "ltr";
// }
// base.InitializeCulture();
//}
}
You had previously used Response.RedirectPermanent("~/en/Default.aspx");. A complying browser would remember this and always redirect you there.
Clear your browser cache and try again :)
As a side note, use Redirect instead of RedirectPermanent. If I'm accessing www.mysite.com from a browser and www.mysite.com RedirectPermanent's me to www.myothersite.com, a complying browser would remember this and for all future requests to www.mysite.com, it would call www.myothersite.com.

How to redirect to a particular page after getting logged in, in membership?

I am using asp.net membership, I have few pages at the root like loin, register, forget pass, that are accessible to all users before they log in or not registered, I want to stop these pages to accessible once user get logged in, I mean if a user manually type the URL in the Address Bar it allows to access those pages how to prevent this?
Also, I am facing a problem how to redirect to a particulate page after getting logged in.
to redirect once Logged in check FormAuthentication.RedirectfromLoginPage
public void Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
and you can check whether user is authenticated or not by
Page.User.Identity.IsAuthenticated
Check this links for forms authentications
FormsAuthentication
FormAutentication MSDN
You can use UrlReferrer to validate if page is accessed by navigation. UrlReferrer gets information about the URL of the client's previous request that linked to the current URL. for details visit this link
if(Request.UrlReferrer == null)
{
//code to redirection to login page
}

How to check is page is redirected from previous page or not in asp.net

In Page 1 on button click I redirect the page to page 2 with msgid, and in page 2 in page load I check whether the previous page is valid. So i check (this.Page.PreviousPage != null) but this is always null and the page gets redirected to page 1. I am doing this so that no one can change the msgid in the url. How can I solve this issues. thanks
Page1:
int msgid = Convert.ToInt32(Hidden_MsgID.Value);
string url = "Page2.aspx?MsgID=" + msgid;
Response.Redirect(url);
Page2:
if (this.Page.PreviousPage != null)
{
}
else
{
Response.Redirect("Page1.aspx");
}
instead of response.redirect I used server . transfer and it works
Server.Transfer(string.Format("ResponseMetric.aspx?MsgID={0}", msgid));
PreviousPage does only work with Server.Transfer and/or cross-page-posting: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx
elements for your solution available here: work with this.Request.UrlReferrer
Maybe you can use a session variable to check if the flow is followed as well..
Before your redirect you can set
Session["PREVPAGE"] = "fooo.aspx";
And retrieve it in the page load of the second page..

login asp.net redirect with parameters

I'm writing login page where login is default "Admin" and password is reading from xml file (FileUpload control).
How to redirect to main page, and to know what is path to this file("FileUpload.Name")? Which method of redirecting is appropiate? (sth like redirecting with parameters...but how?
You question is not clear but to redirect the user back to man page after successful login do this:
//I assume a bool variable UserIsValid which you set after validating the user
if (UserIsValid)
{
//If user was redirected back to login page then go back to requested page
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage("User_name", false);
}
else
{
//Set an Auth cookie
FormsAuthentication.SetAuthCookie("User_name", false);
//And then redirect to main page with you parameters if any
Response.Redirect("mainPage.aspx?parameter1={0}&parameter2={1}", param1, param2);
}
}
else
{
//User was not valid, do processing
}
You can get the physical path of a file placed inside your application folder by Server.MapPath
Lets have some examples
[Root_Folder]/FileName.ext
string physicalPath = Server.MapPath("~/FileName.ext");
if file is inside a folder like
[Root_Folder]/App_Data/FileName.ext
string physicalPath = Server.MapPath("~/App_Data/FileName.ext");
physical path will contains like the following string
C:\Websites\MyXYZ\FileName.ext
Now you want to redirect to Home.aspx
Response.Redirect("~/Home.aspx");
if you want to send any querystring parameter, just append as string preceding ? and separated by &
// append as many as required
Response.Redirect("~/Home.aspx?myParam1=" + param1Variable + "&param1=" + param2Variable);
Why don't you try asp.net built in controls i.e. ASP.NET Login Controls Overview
How to: Create an ASP.NET Login Page
Configuring an ASP.NET Application to Use Membership
Suggestion; don't get weird with asp.net login controls if you find your simple solution for accessing file and redirecting.

Detect Session Timeouts / Distinguish Between First Visit & Session Timeout

When a user goes to the sign in page, I want to detect if their session timed out and was redirected to this page, so a friendly message could be displayed.
I set isTimeout = true when the session is a new session and when the cookie["ASP.NET_SessionId"] is not null. But isTimeout was set to true when if it was a first visit too. How do I distinguish the first visits from timeouts?
Thanks in advance!
In your Global.asax there is a method called Session_End to handle just this.
You can use this to add whatever functionality you need. Such as setting TempData["IsTimeout"] to true (if you are using ASP.NET MVC). This will then persist past the redirect and is accessible on your log in view. It will then be destroyed.
E.g. In your Global.asax.cs
protected void Session_End(Object sender, EventArgs e)
{
TempData["IsTimeout"] = true;
}
In your log in view:
<%: ((bool)(TempData["IsTimeout"] ?? false)) ? "For security reasons you were timed out, please log in again" : "" %>

Categories