Hi Rockstar8,
Use Global.asax to check if User is available in id database or not when Each Page is Requested using the Application_BeginRequest event.
Add a WebForm with name Error.aspx to display the message.
Error.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
U r not authorized to use this site.
</div>
</form>
</body>
</html>
Global.asax
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Error", // Route name
"Default.aspx"
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (!Request.RawUrl.ToLower().Contains(".aspx"))
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name FROM Customers WHERE Name = @Name", conn))
{
cmd.Parameters.AddWithValue("@Name", userName);
conn.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
conn.Close();
if (!string.IsNullOrEmpty(name))
{
Response.RedirectToRoute("Default");
}
else
{
Response.RedirectToRoute("Error");
}
}
}
}
}
}
}
When you are trying to access any page it will first check the Request url and if it doesnot contain aspx extension then check for login user name and check with database record and redirect to respective page.