Session checking in asp.net - asp.net

I was assigned to a older project been done in asp webforms. So in every page load I found code like
if (HttpContext.Current.Session["UserDetails"] != null)
For checking if session is active for visiting the page. Is there any single point where I can write this code so that if user is inactive loginPage is presented.

Maybe you could achieve your task with a HTTPModule:
Example from MSDN
using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
// test here your session
}
}
private void Application_EndRequest(Object source, EventArgs e)
{
}
public void Dispose() { }
}
You should register this module in your web.config:
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>

If you have controller page, how about this way?
Controller page.
[SessionExpireFilter]
public void functionname()
{
//you're function region page?
}
New createpage.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session["UserDetails"] == null)
{
filterContext.Result = new RedirectResult("~/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}

Related

Why could not access Session using asp.net web api?

In my ASP.NET Web API project, i could access Session object in local (both debug and release model).
But when i deploy it to the server, it doesn't work.
Global.asax
public override void Init()
{
this.PostAuthenticateRequest +=MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
UserApiController.cs
[HttpGet]
public string GetVerificationCode(string mobileNumber)
{
if (!string.IsNullOrWhiteSpace(mobileNumber) &&
Regex.Match(mobileNumber, #"^1\d{10}$", RegexOptions.IgnoreCase).Success)
{
string VerificationCode = "1234";
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["VerificationCode"] = VerificationCode;
}
return VerificationCode;
}
throw new ArgumentException("Phone number format is incorrect");
}
[HttpGet]
public string GetSessionString()
{
if (HttpContext.Current.Session != null)
{
return HttpContext.Current.Session["VerificationCode"].ToString();
}
return string.Empty;
}
Why it doesn't work?

how can i call method in web page from class library

I have a page sample.aspx. In this file page I use ajax to call a handler which in class library. I do some job in class lib. After doing this, I want to call method from sample.cs.
For example:
addstudent.aspx page calls ajax request to addstudent.ashx (this code is in handler.cs). I am adding student with params, and after adding students I want to call a method which is in addstudent.cs for example public afteraddingstudent(){}
How can I call after adding student in class lib?
Make your afteraddingstudent method as public static and after that you can call this method in handler as
public static void afteraddingstudent()
{
}
Handler,
WebApplication1.addstudent.afteraddingstudent();
//in my Handler class lib,it is separated project
public class gnric : IHttpHandler, IRequiresSessionState
{
public enum DBAction
{
INSERT = 0,
UPDATE = 1,
DELETE = 2
}
public class DatabaseEventArgs : EventArgs
{
private DBAction prmAction;
private int prmID;
public DatabaseEventArgs(DBAction Action, int ID)
{
this.prmAction = Action;
this.prmID = ID;
}
public int ID
{
get { return prmID; }
}
public DBAction Action
{
get { return prmAction; }
}
}
public delegate void DBChangeEventHandler(object sender, DatabaseEventArgs e);
[Category("DB"), Description(" when a record is Inserted, Updated, or Deleted.")]
public event DBChangeEventHandler DBChange;
protected virtual void OnDBChange(DatabaseEventArgs e)
{
if (DBChange != null)
DBChange(this, e);
}
public void ProcessRequest(HttpContext context)
{
//DO SOME DBJOBS
OnDBChange(new DatabaseEventArgs(DBAction.UPDATE, 22));
//in my apsx file
protected void LNA_DBChange(object sender,HandlerClass.gnric.DatabaseEventArgs e) //how can I bind this method
{
EasySQL DBA = new EasySQL();
DBA.cmd("INSERT INTO TEST ALAN VALUES(3)");
}

How do I get my EntitySetController to be visible to my route?

I created an EntitySetController that looks like this:
public class OrdersController : EntitySetController<Order,Guid>
{
private readonly PizzaCompanyEntities _context = Factories.DataFactory.GetPizzaContext();
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
public override IQueryable<Order> Get()
{
return _context.Orders;
}
protected override Order GetEntityByKey(Guid key)
{
var result = _context.Orders.FirstOrDefault(o => o.Id == key);
if (result == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return result;
}
}
In an existing MVC 4 web application.
I configure the route as follows:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapODataRoute("PizzaApi", "odata", GetImplicitEdm());
}
private static IEdmModel GetImplicitEdm()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Order>("Orders");
builder.EntitySet<Pizza>("Pizzas");
builder.EntitySet<Pizzas_To_Orders>("PizzasToOrders");
builder.EntitySet<Size>("Sizes");
builder.EntitySet<Status>("Statuses");
builder.EntitySet<Pizzas_To_Toppings>("PizzasToToppings");
return builder.GetEdmModel();
}
}
And execute the configuration as follows:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
But when I execute my route at http://localhost:29064/odata/Orders I am getting a 404 and a message "The controller for path /odata/Orders was not found or does not implement IController.
I cannot figure out what I am missing to get the route registered and the controller running. I have done a similar application from scratch and have not had this trouble.
How do I get my OData route working?

asp.net Nhibernate session managment

I implement standart scenario in asp.net session per reqest.
My asp.net module:
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
var session = SessionManager.SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
var session = SessionManager.CurrentSession;
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
throw new ApplicationException("Error committing database transaction", ex);
}
finally
{
session.Close();
}
}
CurrentSessionContext.Unbind(SessionManager.SessionFactory);
}
}
My sessionManager is thread-safe singletone:
public class SessionManager
{
private readonly ISessionFactory sessionFactory;
public static ISessionFactory SessionFactory
{
get { return Instance.sessionFactory; }
}
private ISessionFactory GetSessionFactory()
{
return sessionFactory;
}
public static ISession OpenSession()
{
return Instance.GetSessionFactory().OpenSession();
}
public static ISession CurrentSession
{
get
{
if (!CurrentSessionContext.HasBind(Instance.GetSessionFactory()))
return null;
return Instance.GetSessionFactory().GetCurrentSession();
}
}
public static SessionManager Instance
{
get
{
return NestedSessionManager.sessionManager;
}
}
private SessionManager()
{
Configuration configuration = new Configuration().Configure();
sessionFactory = configuration.BuildSessionFactory();
}
class NestedSessionManager
{
internal static readonly SessionManager sessionManager =
new SessionManager();
}
}
The main idea open session in begin of request and then use session through SessionManager.CurrentSession;
Session is stored in configured context:
<property name="current_session_context_class">web</property>
My repository:
public class RepositoryNew<T> : BaseRepository<T>, IDisposable
{
public RepositoryNew()
{
if (NHibernateSession == null)
//Start session for not web version
}
public void Dispose()
{
//flush session for not web version
}
protected override sealed ISession NHibernateSession
{
get
{
return SessionManager.CurrentSession;
}
}
}
Usage
protected void Page_Load(object sender, EventArgs e)
{
var repo = new RepositoryNew<Client>()
clients = repo.GetAll();
}
By some reason this repository doesn't use opened session in module.
CurrentSessionContext.HasBind(Instance.GetSessionFactory())
returns false, so my code starts second session in request.
At debugger I see that I have instantieted my SessionManager twice.
My be I have two different ISesssion factories.
I haven't ideas yet what's wrong. I have spent on it a lot of hours.
Maybe another thing open session in Http Begin Request because every http request will open new session like request static image you must change this strategy to eliminate this unnecessary session in every Http request you can read this blog and change your strategy http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx
It was strange error. When I remove link to SessionManager from my project, it starts work properly.

Get the route when unauthenticated/logout with mvc?

I have this piece of code:
public class Authenticate : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.HttpContext.Response.Redirect("/");
}
}
}
I was wondering if it is possible to make it redirect to the view for action="Login" controller="AdminLogin"? And how do I pass some message to the login view that tells "you need to login to access that" or similar?
/M
Here is how I solved the redirect-part:
public class Authenticate : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
RedirectToRoute(filterContext,
new
{
controller = "AdminLogin",
action = "AdminLogin"
});
}
}
private void RedirectToRoute(ActionExecutingContext context, object routeValues)
{
var rc = new RequestContext(context.HttpContext, context.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc,
new RouteValueDictionary(routeValues)).VirtualPath;
context.HttpContext.Response.Redirect(url, true);
}
}
Not sure if it is optimal but seems to do the job correctly

Resources