I have a basic project with a menu bar that the server executes on each page. I want to prevent the access to the pages for unregistered users, so I added this code
if (Session["username"] == null)
Response.Redirect("HomePageWebSite.aspx");
When I load the HomePage by its self it works normaly, but when I use this code, the browser says that it can't find this page(unable to access this page). I checked the url of the homepage and it's the same one that the server can't access to.
How can I solve this problem?
If your home page is in the root change the code as below:
if (Session["username"] == null)
Response.Redirect("/HomePageWebSite.aspx");
The "/" in the beginning will always lookup from the root directory. If you do not give the "/" it will always lookup in the current directory which will results in problems if you have nested directories.
Related
I have an ASP.NET Web Application (using Razor pages not controllers) and I am trying to amend the register (identity) page so that once the user has registered (by an admin whos logged in already) it navigates to a Manage roles page and passes the UserId of the user just created.
This is my folder structure:
Currently I'm on the register page which is within the following path:
Areas/Identity/Pages/Account/Register.cshtml
and I am trying to navigate to a page thats simply within the Pages folder: Pages/ManageRoles.cshtml
Here is my code:
return RedirectToPage("./ManageRoles", new { id = user.Id });
but it doesn't work and gives me an error saying No page named './ManageRoles' matches the supplied values. I have also tried the code without the ./ and it still gave me the same error. I have also tried it without the userId part and it still didnt work.
Could someone help me?
Changed it to this and it worked:
return RedirectToPage("/ManageRoles", new { UserId = user.Id });
I'm developing a universal app using MVVM (light) and I'm trying to integrate OneDrive using the SDK. Each of my pages have a ViewModel associated with them.
I have a start up page (OneDrivePromptPage) where I offer the user to either sign in to Microsoft OneDrive or skip the sign in process.
When the user clicks on the Skip button, it calls the relevant command in my OneDrivePromptViewModel and navigates to my MainPage by calling:
this._navigationService.Navigate(typeof(MainPage));
The same applies when the user clicks on the Sign button and it prompts the user for their OneDrive credentials and if successfully logged in, it navigates to my 'MainPage'.
Now, here's my problem. When signs in successfully to OneDrive, I set a flag (IsSignedIn=true) to a container and save it to my storage (RoamingSettings).
All of the above works fine but I'm facing a problem where when I start the application again, it checks OneDrivePromptViewModel's constructor if the IsSignedIn value from the storage is set to true. If it is, I'll try to automatically sign in to OneDrive. If successful, I want to navigate to my 'MainPage' but this won't work.
It calls the same navigate code as above, doesn't throw any errors but it doesn't navigate to my 'MainPage' and ends up displaying my "Prompt" page.
public OneDrivePromptViewModel(INavigationService navigationService,
ISettingsDataService settingsDataService)
{
this._navigationService = navigationService;
this._settingsDataService = settingsDataService;
bool isSignedIn = false;
isSignedIn = this._settingsDataService.
GetItem<bool>("MyStoreApp", "IsSignedIn");
if (isSignedIn && !MyOneDrive.IsSignedIn())
{
ExecuteSignInCommand();
}
else if (isSignedIn && MyOneDrive.IsSignedIn())
{
NavigateToMainPage();
}
}
Any ideas why it's not navigating to the relevant page. Is it because I'm calling this from the constructor. If that's not the correct place to call it from, where should I call this from?
I'm not even sure, I should be loading the OneDrivePromptPage? Should I be performing this checks in a method of some sort before loading either OneDrivePromptPage or MainPage and perform the same checks mentioned above, but where do I put this method? In my App.cs?
Thanks.
In a recent Universal app I check for something similar, but initiate this in the OnLaunched event of the App.xaml.cs
Making sure based on the isSignedIn check that I navigate to the correct page like so:
bool navigated = rootFrame.Navigate(isSignedIn ? typeof(MainPage) : typeof(PromptPage);
You could try to see if this also works in your scenario
I am trying to move the content of a textbox on the from StudentRegistration to the form MyProfile by following a tutorial on YouTube. However when I try to reference the StudentRegitration Page in my code, I get the error that the type or namespace cannot be found.
In the tutorial I can see that in their code they have a namespace, however my website does not. Could anyone tell me what to do in order to be able to reference StudentRegistration without getting an error?
I should have stated that I have a website not a web app. I have found that websites do not have a default namespace. How would I go about accessing the StudentRegistration without referencing a namespace?
public partial class MyProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
lblEmail.Text = StudentRegistration.STextBoxEm;
}
}
}
Rather than answer your question directly, I'd like to point out another issue with your code that will probably prevent it from working. You should refer to the documentation on the PreviousPage property at: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage%28v=vs.110%29.aspx
It does NOT work like this:
user visits /StudentRegistration.aspx
user does stuff
user submits the form on /StudentRegistration.aspx
server redirects the user to /MyProfile.aspx
MyProfile class knows that PreviousPage = the class from /StudentRegistration.aspx
Instead, the description from the msdn reference page linked above stipulates that the PreviousPage property only works on this scenario:
user visits /StudentRegistration.aspx
user does some stuff
user submits form on /StudentRegistration.aspx
server transfers request to the MyProfile class
this does not mean that the url has changed to /MyProfile.aspx for the user, this means that the server is going to treat the current request to /StudentRegistration.aspx as if it were actually a request to /MyProfile.aspx
the user ends up seeing the result of what would normally be /MyProfile.aspx on /StudentRegistration.aspx
Now, your code may actually want that, but the fact that you have:
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
// this should be
// StudentRegistration LastPage = (StudentRegistration)PreviousPage;
}
makes me think that you have misinterpreted the somewhat misleadingly named PreviousPage property. For a sample of how to persist state across multiple page loads in .NET, I would recommend reading up on SessionState. It has a somewhat complicated name, but does more of what you would want in this scenario:
http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx
An added bonus is that you do not need to reference one class from another, so you fix your current bug later on. Additionally, even if you did resolve your potential namespace error, the issue that I outlined earlier will cause the value of the text field to be blank if your code is working as I suspect.
You are sending data from a source to a target - e.g. StudentRegistration -> MyProfile
You have options because at the end of the day, it is HTTP. Aside from "persistence" (Session), and the tutorial you are following, a "simpler" way is to use ButtonPostBackUrl.
All it means is that you are POSTing data to the target page. The target page (MyProfile) will have to validate and parse the posted data (Request.Form). This way you don't have to manage things like Session state.
How can I set up my page load event in my code behind to redirect to an url that has an https prefix? I would need it to work with urls that have query strings attached too.
It's one thing to construct a link that goes straight to the https page, but I don't want the user to be able to manually change it to an http page.
Also I don't want to do it with javascript because it might be turned off.
I'm guessing a regular expression?
We mark our SSL Required pages with a special attribute ForceSslAttribute. Then we have a HttpModule that pulls down the current page's class and inspect it's attributes.
If the attribute is present on the page, it takes the exact url that was passed and changes the protocol from http to https then calls a redirect.
There's probably a bit simpler way of doing it, but that's how it's done for us.
Attribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public sealed class ForceSslAttribute : Attribute
{
// Marker Attribute
}
Page Example (CodeBehind):
[ForceSsl]
public partial class User_Login : Page
{
//...
}
You can figure out the type of the page like this:
HttpContext.Current.CurrentHandler.GetType()
All Page's implement IHttpHandler and when you're visiting a page, it'll work.
The cool part about this method is you can mark anything that's an IHttpHandler and it'll force the redirect too :)
Add this at the top of your Page_Load
if (Request.ServerVariables["HTTPS"] != "ON")
{
Response.Redirect("https://" + Request["HTTP_HOST"] + Request.RawUrl);
}
I use the following in Global.asax Application_BeginRequest
If needsSSL <> Request.IsSecureConnection Then
If needsSSL Then
Response.Redirect(Uri.UriSchemeHttps + Uri.SchemeDelimiter + Request.Url.Host + Request.Url.PathAndQuery, True)
Else
Response.Redirect(Uri.UriSchemeHttp + Uri.SchemeDelimiter + Request.Url.Host + Request.Url.PathAndQuery, True)
End If
End If
There is an IIS7 module for URL rewriting. Very handy, but you need access to the IIS and it requires some time to learn how to write the rules. A simple http->https rule is a matter of seconds.
Just be careful because any rules you add will be stored in your web.config, so don't delete/override it or you will have to write them again.
Forcing SSL using ASP
To force SSL using ASP, follow these steps:
Click Start, click Run, type Notepad, and then click OK.
Paste the following code into a blank Notepad document. On the File menu, click Save As, and then save the following code in the root of your Web server as an include file named ForceSSL.inc:
<%
If Request.ServerVariables("SERVER_PORT")=80 Then
Dim strSecureURL
strSecureURL = "https://"
strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
strSecureURL = strSecureURL & Request.ServerVariables("URL")
Response.Redirect strSecureURL
End If
%>
For each page that requires SSL, paste the following code at the top of the page to reference the include file from the previous step:
<%#Language="VBSCRIPT"%>
<!--#include virtual="/ForceSSL.inc"-->
When each page is browsed, the ASP code that is contained in the include file detects the port to determine if HTTP is used. If HTTP is used, the browser will be redirected to the same page by using HTTPS.
I have two pages, NonMember.aspx and Member.aspx. If a user comes to the site, they will go to NonMember.aspx as soon as they login, I want them to immediately be redirected to Member.aspx, but instead of doing this, it is staying on NonMember.aspx. The user actually has to go click on the menu item again to get to Member.aspx.
The links are located at http://abc.com/tools/NonMember.aspx
and http://abc.com/tools/Member.aspx.
I was doing:
System.IO.Path.GetFileNameWithoutExtension(Request.Url.ToString());
but I am thinking there is a better way, especially since I have multiple default.aspx pages and this could pose a problem
Here is more detail on what exactly I am doing:
When I run the site on my local development machine, the NonMember page points to:
http://testserver/tools/NonMember.aspx.
Requet.Url.AbsolutePath points to /testserver/tools/NonMember.aspx.
Then I am doing this:
if(url == "~/tools/NonMember.aspx")
{
Response.Redirect("~/tools/Member.aspx");
}
The above is not working and I can check if url is equal to /testserver/tools/NonMember.aspx because if I deploy to liveserver, it will fail.
When using Forms Authentication for an ASP.NET application, it will automatically redirect you to the page you were viewing before you logged in. This is why you are redirected back to the NonMember.aspx page.
It would be better if you had just one member page, and perform a check in the page to see if the user is authenticated, if so, display the member content, otherwise, display the non-member content.
Then, when the user logs in and is redirected back to the page, they will see the member content.
If you are insistent on keeping the two separate pages, then in your check you simply have to see if the current user is authenticated (through the IsAuthenticated property on the User that is exposed through the page) and then redirect to your members page. If you are on the NonMember page, you don't need to check to see what the url is (unless this is MVC, which you didn't indicate).
If you have the HttpResponse object, you can use HttpResponse.Redirect
You should check your cookie or session variable to see if the user is logged in and then use a Response.Redirect to move them to the member page.
I'm not sure I get your scenario but, let's try.
If you have public pages, the login page and private pages (member pages) and once you authenticate your users you want them to browse ONLY the private part of your website, you should check early in the processing steps (AuthorizeRequest would be a good phase) if the request comming in is for a public or for the login page which you also consider public and redirect to your private page from there (like...having a "home" page for the member area of the site and always redirecting to it once you get an authenticated and properly authorized request to some public URL of your site).
EDIT: You should check for Request.FilePath
I ended up just doing the following:
if(Authenticated)
{
string path = Request.UrlReferrer.AbsolutePath;
if (path.EndsWith("/tools/NonMember.aspx"))
{
Response.Redirect("~/tools/Member.aspx");
}
}