Membership API ASP.NET - asp.net

It is necessary to register as soon as this user directly login
protected void Button1_Click(object sender, EventArgs e)
{
Membership.CreateUser(FNBox.Text, PassBox.Text, EmailBox.Text);
FormsAuthentication.RedirectToLoginPage(FNBox.Text);
}
Error:
"Could not find the resource.
Description: HTTP 404. Perhaps the desired resource (or one of its dependencies of components) is removed, has a different name or is temporarily unavailable. Look at the following URL-address and make sure it is correct.
The requested URL: / OrderTest2/login.aspx "
protected void LoginButton_Click(object sender, EventArgs e)
{
Control lgnview = (Control)LoginView2.FindControl("LoginForm");
TextBox usrbox = (TextBox)lgnview.FindControl("UserName");
TextBox pasbox = (TextBox)lgnview.FindControl("Password");
string user = usrbox.Text;
string pass = pasbox.Text;
if(Membership.ValidateUser(user,pass))
{
FormsAuthentication.RedirectToLoginPage(user);
}
}
This is work normally

Your default redirect login page is wrong. As you can see, you are getting a 404 error which means that IIS cannot find your OrderTest2/login.aspx page. Verify your path.

You can set the defaultUrl path in your web.config as below to a valid page path, this will fix the problem.
<authentication mode="Forms">
<forms loginUrl="/OrderTest2/login.aspx" defaultUrl="myCustomLogin.aspx" cookieless="UseCookies" />
</authentication>

Related

URL Rewriting exceptional case for removing .aspx extension

My scenario is: I have a website which is ASP.NET WebForm. Users can create their own page on my web site, their page url would be something like this: (MyWebsite.com/UserPage). but It is actually: (MyWebsite.com/UserPages.aspx?q=UserPage). It means when you enter the url (MyWebsite.com/UserPage) It rewrites the url and shows you (MyWebsite.com/UserPages.aspx?q=UserPage) (but the address bar is always like (MyWebsite.com/UserPage).
Here's my code in my "UrlRewriting" class:
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.Path.Contains("/") && !app.Request.Path.Contains(".") && app.Request.Path.IndexOf("/") == app.Request.Path.LastIndexOf("/"))
{
string userPageTitle = app.Request.Path.Substring(app.Request.Path.IndexOf("/") + 1);
if (!string.IsNullOrEmpty(userPageTitle ))
{
app.Context.RewritePath(string.Format("UserPages.aspx?q={0}", userPageTitle));
}
}
}
Now here's my problem: as I said my project is ASP.NET WebForm, (So, all of pages have .aspx extension) I wanted to remove the .aspx extension in my Urls, I've tried some codes in web.config which were working properly (In normal cases), but In my case, if you enter (MyWebsite.com/UserPage) It will be considering this "UserPage", as "UserPage.aspx". How can I handle this?
I usually do this with Routing which is available in ASP.NET Web Forms 4+.
You register your routes (URL patterns) in Global.asax, and specify which ASPX page will handle that URL.
This example would have UserPage.aspx handle all URLs that weren't otherwise handled by other ASPX pages.
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("UserPageRoute", "{*url}", "~/UserPage.aspx");
}
Then in your UserPage.aspx you can determine the URL requested by looking at the Request.Url object, eg. Request.Url.PathAndQuery.
Note that you may need some extra web.config settings for this to work, eg (to manage extensionless URL requests)...
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />

Ho work locally with <httpCookies requireSSL="true" /> on?

So, if I set my my web.config to:
<httpCookies requireSSL="true" />
.. I can't run the application locally. How can I bypass this?
I have tried global.asax instead:
protected void Session_Start(object sender, EventArgs e)
{
// Secure Session cookie
if (Request.IsSecureConnection)
{
Response.Cookies["ASP.NET_SessionId"].Secure = true;
}
}
.. but this does not seem to work (Inpector shows the cookie as unsecure).
Ideas?
Ended up switching to a local SSL dev environment, using the steps in this post:
https://dotnetcodr.com/2015/09/18/how-to-enable-ssl-for-a-net-project-in-visual-studio/

Server.ClearError() with page refresh

I am using ASP.NET custom error page in my application. Following is the web.config file entry for CustomErrors tag
<customErrors mode="On" defaultRedirect="Error.aspx" redirectMode="ResponseRewrite" />
Following is the code snippet on Error.aspx page
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Exception ex = Server.GetLastError();
if(ex != null)
{
CommonUtils.SendException(ex.Message.ToString(), ex.StackTrace.ToString());
Server.ClearError();
}
}
}
If "ex" is not null, code will send the exception email. This works fine.
After sending email, I want to clear all the errors so that no email will be sent in case users hits the refresh button. But even after using Server.ClearError, there is a value return by Server.GetLastError() When page is posted back.
Your code should be rewritten to something like this:
Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception ex= Server.GetLastError();
CommonUtils.SendException(ex.Message.ToString(), ex.StackTrace.ToString());
}
And the Page_Load event of error page should be empty then. As you can read in this MS article: https://support.microsoft.com/en-us/kb/306355 Server.ClearErrors stops error propagation, so If you call it on the page error will not be handled by Application_Error event. If you don't call it in Application_Error then application will look for customErrors declaration in web.config redirect to that page.
If you do not call Server.ClearError or trap the error in the
Page_Error or Application_Error event handler, the error is handled
based on the settings in the section of the Web.config
file. In the section, you can specify a redirect page
as a default error page (defaultRedirect) or specify to a particular
page based on the HTTP error code that is raised. You can use this
method to customize the error message that the user receives.
If an error occurs that is not trapped at any of the previous levels
in your application, this custom page is displayed. This section
demonstrates how to modify the Global.asax file so that
Server.ClearError is never called. As a result, the error is handled
in the Web.config file as the last point to trap the error.

How to url redirect/rewrite .asp into .aspx

I'm running in the Cassini developer server inside Visual Studio 2012, and I need to redirect clients from the legacy .asp pages to .aspx pages.
Note: Ideally I would redirect clients from .asp to a friendly url, and then internally do a rewrite to .aspx
POST /ResetClock.asp
HTTP/1.1 307 Temporary Redirect
Location: //stackoverflow.us/ResetClock
And then internally:
POST /ResetClock
rewrites into /ResetClock.ashx (Yes, I changed it to .ashx; that's the virtue of url rewriting).
Like what Hanselman did
This is a lot like what Scott Hanselman did:
Request for /foo.html
gives the client a redirect to /foo
client request for /foo
is re-written into /foo.html
The attempted hack
I tried the hack solution; alter the .asp page to force a redirect to the .ashx (and live to fight with the url re-write syntax another day):
ResetClock.asp
<%
Response.Redirect("ResetClock.aspx")
Response.End
%>
Except that Cassini does not serve .asp pages at all:
This type of page is not served.
Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.asp' may be incorrect. Please review the URL below and make sure that it is spelled correctly.
Requested URL: /WebSite/FetchTimes.asp
Which points to a related issue. The solution I end up using cannot require anything that isn't already available on the IIS7.5. And it cannot require anything that needs access to the IIS Admin tools; and must exist entirely within the web-site (e.g. the web.config).
The question
How do I re-write .asp into something more ASP.net-ish?
Edit: Changed GET to a POST to thwart nitpickers who wonder why the 307 Temporary Redirect and not 302 Found or 303 See Other.
The solution is to create an IHttpModule. HttpModules let you intercept every request, and react as you desire.
The first step is to create the plumbing of an IHttpModule:
class UrlRewriting : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
application.EndRequest += new EventHandler(this.Application_EndRequest);
}
public void Dispose()
{
//Nothing to do here
}
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
}
private void Application_EndRequest(object sender, EventArgs e)
{
}
}
And then register our HttpHandler in the web.config file:
web.config:
<configuration>
<system.web>
<httpModules>
<add name="UrlRewriting" type="UrlRewriting"/>
</httpModules>
</system.web>
</configuration>
Now we have a method (Application_BeginRequest) that will run every time a request is made.
Issue client redirect if they ask for ASP page
The first order of business is redirect the client to a "clean" form. For example, a request for /File.asp is redirected to /File:
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
//Redirct any requests to /File.asp into a /File
if (context.Request.Url.LocalPath == VirtualPathUtility.ToAbsolute("~/File.asp"))
{
//Be sure to issue a 307 Temporary Redirect in case the client issued a POST (i.e. a non-GET)
//If we issued 302 Found, a buggy client (e.g. Chrome, IE, Firefox) might convert the POST to a GET.
//If we issued 303 See Other, the client is required to convert a POST to a GET.
//If we issued 307 Temporary Redirect, the client is required to keep the POST method
context.Response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
context.Response.RedirectLocation = VirtualPathUtility.ToAbsolute("~/File");
context.Response.End();
}
}
And then the internal rewrite
Now that the client will be asking for /File, we have to re-write that internally to an .aspx, or in my case, an .ashx file:
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
//Redirct any requests to /ResetClock.asp into a /File
if (context.Request.Url.LocalPath == VirtualPathUtility.ToAbsolute("~/ResetClock.asp"))
{
//Be sure to issue a 307 Temporary Redirect in case the client issued a POST (i.e. a non-GET)
//If we issued 302 Found, the buggy client might convert the POST to a GET.
//If we issued 303 See Other, the client is required to convert a POST to a GET.
//If we issued 307 Temporary Redirect, the client is required to keep the POST method
context.Response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
context.Response.RedirectLocation = VirtualPathUtility.ToAbsolute("~/ResetClock");
context.Response.End();
}
//Rewrite clean url into actual handler
if (context.Request.Url.LocalPath == VirtualPathUtility.ToAbsolute("~/ResetClock"))
{
String path = "~/ResetClock.ashx"; //no need to map the path
context.Server.Execute(path, true);
//The other page has been executed
//Do not continue or we will hit the 404 of /ResetClock not being found
context.Response.End();
}
}
IIS contains some basic url redirection
Starting with some unknown version of IIS, they added a (now mocked) form of URL Rewriting. It doesn't issuing a client redirect, only an internal re-write. But at least it could be used to solve my problem (responding to an ASP page with ASP.net content):
web.config
<configuration>
<system.web>
<urlMappings>
<add url="~/ResetClock.asp" mappedUrl="~/ResetClock.ashx"/>
</urlMappings>
</system.web>
</configuration>
The client will still appear to have found a resource at /ResetClock.asp, but the guts of the response will have come from /ResetClock.ashx.
Note: Any code is released into the public domain. No attribution required.

asp.net mvc http context having different values in global.asax and in mvc's controller context and filter context

I am having different values of HttpContext object in my global.asax Application_AuthenticateRequest method and on the Authorize attribute filterContext's HttpContext and also the controller Context.
I have set the application to run Single Sign on. Here is my web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name="FormsAuth" timeout="2880000" domain="domain.com" slidingExpiration="true" defaultUrl="~/home/index"/>
</authentication>
Then on log in, after validating the user, the authentication cookie is set.
FormsAuthentication.SetAuthCookie(userName, true);
Here is the problem now, when the breakpoint is hit on global asax Application_AuthenticateRequest method, the Request.IsAuthenticated is true, but when it hit the Authorize attribute's OnAuthorize method, its filterContext.HttpContext.Request.IsAuthenticated is false. The page will always be redirected to the log on page even though the user is valid.
Can someone explain why is this so? Or any blog forums explaining the internal working of httpcontext in asp.net mvc. It seems Core ASP.NET httpcontext and MVC httpcontext is having different value in this case.
I just made a test using MVC3 and in both cases the IsAuthenticated property returns true if the user was authenticated correctly:
Code used:
Global.asax
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
this.Context.Trace.Warn("From global asax: " + this.Context.Request.IsAuthenticated.ToString());
}
Custom Authorization filter
public class CustomAuthorization : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpContext.Current.Trace.Warn("from attribute: " + filterContext.RequestContext.HttpContext.Request.IsAuthenticated.ToString());
base.OnAuthorization(filterContext);
}
}
I hope this helps you to find the problem

Resources