I'm trying to setup routing in my web application.
It doesn't seem to work with Ninject however. If I comment all the Ninject in my Global.asax, the route works like a charm.
With Ninject in the file, I just get a 404 "The resource cannot be found" when trying to open the route page.
Heres what is in my Global.asax code:
<%# Application Language="C#" Inherits="Ninject.Web.NinjectHttpApplication" %>
<%# Import Namespace="Infrastructure.Storage" %>
<%# Import Namespace="Ninject" %>
<%# Import Namespace="Ninject.Modules" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new SiteModule());
return kernel;
}
public class SiteModule : NinjectModule
{
public override void Load()
{
//Bind<ILogger>().To<NLogger>().InSingletonScope();
//Bind<IAuthentication>().To<Authentication>();
Bind<ISession>().To<LinqToSqlSession>();
Bind<IReadOnlySession>().To<LinqToSqlReadOnlySession>();
//Bind<IReporting>().To<LinqToSqlReporting>();
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("City", "Cities/{id}", "~/test2.aspx");
}
</script>
Anyone have an idea for what could be wrong?
When you use the NinjectHttpApplication class for your asax, you need to change the way the applicationStart & applicationEnd are called.
What's happening is .net automatically wires the methods above to the corresponding events. Because the NinjectHttpApplication already handles the Application_Start, your method won't get called, hence your routes are not registered. You need change that method to
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
RegisterRoutes(RouteTable.Routes);
}
Related
CSRF synchronize token pattern implementation in ASP.net webform app, I have added this <%= System.Web.Helpers.AntiForgery.GetHtml() %> in aspx page and
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
AntiForgery.Validate();
}
and it working perfect fine.
Now, I have requirement of implementing similar changes on 100+ pages and across multiple apps. In the current framework I have Base class for each page\view where i added AntiForgery.Validate(); in overridden method Page_Load(), but how can i add this <%= System.Web.Helpers.AntiForgery.GetHtml() %> code in aspx page through C# code dynamically?
Basically, how to add <%= System.Web.Helpers.AntiForgery.GetHtml() %> to all asp.net web forms dynamically with C# code?
namespace WebAppForXSRF
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
AntiForgery.Validate();
}
}
protected override void OnInit(EventArgs e)
{
LiteralControl literalContols = new LiteralControl();
literalContols.Text = System.Web.Helpers.AntiForgery.GetHtml().ToHtmlString();
this.MasterForm.Controls.Add(literalContols);
}
}
I'm trying to detect Asp.NET Session Timeout to redirect user to a timeout page; i've checked various methods, most of them similar to
http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.2
(if Session.IsNewSession and ASP.NET_SessionId cookie exists, then is a timeout)
The problem is that the "ASP.NET_SessionId" cookie is always present for me, even if i just started debugging, thus giving me always a false timeout flag when starting the web site for the first time.
UPDATE:
For testing, i've just created an Empty Asp.NET Web Application with following codes:
BasePage.cs
using System;
using System.Web.UI;
namespace TestApp.classes
{
public class BasePage : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Context.Session != null)
{
if (Session.IsNewSession)
{
string szCookieHeader = Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
Response.Redirect("sessionTimeout.htm");
}
}
}
}
}
}
Global.asax
using System;
namespace TestApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
var a = "";
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
var b = "";
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
WebForm1.aspx
using System;
using TestApp.classes;
namespace TestApp
{
public partial class WebForm1 : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<sessionState timeout="1"></sessionState>
</system.web>
</configuration>
Then Hit F5, and i will be redirected to sessionTimeout.htm. Why?
You don't have to use cookie when you develop your website. There are other ways to store data, e.g. you can store the data specific to a user in database
Note that "Cookieless = false" attrubute of SessionState element in web.config which means the sessionID of the current session will be saved in the client machine as a cookie
<sessionState cookieless="true" />
Default settings for ASP.NET session state are defined in the machine.config file and can be overridden in the web.config file in the application's root folder. By ensuring that the above line appears in the root web.config file, you enable cookieless sessions
Refer http://msdn.microsoft.com/en-us/library/aa479314.aspx
So check only for Session.IsNewSession and disable cookie
The error I'm getting is
A route named 'xxxxx' could not be found in the route collection.
Parameter name: name
global asax
<%# Application Language="C#" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("test2-testurl", "test2/{category}", "~/test2.aspx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
In page test1 I have coded below like this on button click event:
protected void Button1_Click(object sender, EventArgs e)
{
string url = Page.GetRouteUrl("test2-testurl", new { category = "laptops" });
Response.RedirectToRoute(url);
}
Maybe try this (remove 'test2'):
routes.MapPageRoute("test2-testurl", "{category}", "~/test2.aspx");
Update:
try just to redirect to page this way
Response.Redirect("page2/laptops");
Example:
// add route
routes.MapPageRoute("ad-view", "view/{ad-id}", "~/ad_view.aspx");
// on page I usualy bind values in repeater to links like this:
<asp:HyperLink ID="TitleHL" NavigateUrl='<%# "view/" + Eval("ad_id") %>' runat="server">
// to redirect from code-behind i'll use:
Responce.Redirect("view/" + ad_id);
I have followed a few tutorials online and they all seem to show the same logic for .net routing using ASP.net web forms. When I execute the URL below I get a 404 error. Test.aspx is in the root folder of this application.
http://www.mydomain.com/member/abc
Here is my global.asax contents:
<%# Application Language="C#" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"TestABC",
"member/{name}",
"~/Test.aspx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
Is there something I need to do with my web.config file?
Any help is greatly appreciated.
I'm guessing that your routing module is not triggered when you hit the iis server.
As a test to verify that this is the cause : change your webconfig to run all managed modules upon a request.
You need to set this :
<modules runAllManagedModulesForAllRequests="true">
If that solved it you can go read this resource on why to not do that :)
What I am looking is something similar to the below (http://github.com/ninject/ninject.web.mvc):
README.markdown
This extension allows integration between the Ninject core and ASP.NET MVC projects. To use it, just make your HttpApplication (typically in Global.asax.cs) extend NinjectHttpApplication:
public class YourWebApplication :
NinjectHttpApplication { public
override void OnApplicationStarted()
{
// This is only needed in MVC1
RegisterAllControllersIn("Some.Assembly.Name");
}
public override IKernel
CreateKernel() {
return new StandardKernel(new SomeModule(), new SomeOtherModule(),
...);
// OR, to automatically load modules:
var kernel = new StandardKernel();
kernel.AutoLoadModules("~/bin");
return kernel; } }
Once you do this, your controllers will be activated via Ninject, meaning you can expose dependencies on their constructors (or properties, or methods) to request injections.
Just want share how did I solved it using Visual Studio 2008
For those of you guys been to www.tekpub.com code below is kinda familiar, Yes! your correct code below is from Mastering ASP.NET MVC 2.0 series, and a demonstration of how to use NLog
Needed Reference:
Ninject.dll
Ninject.Web
NLog.dll
Global.asax :
<%# Application Language="C#" Inherits ="Ninject.Web.NinjectHttpApplication" %>
<%# Import Namespace="App_Code.Infrastructure.Logging"%>
<%# Import Namespace="Ninject.Modules"%>
<%# Import Namespace="Ninject"%>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
protected override void OnApplicationStarted()
{
//base.OnApplicationStarted();
Container.Get<ILogger>().Info("Application Started");
}
protected override IKernel CreateKernel()
{
return Container;
}
static IKernel Container
{
get
{
return new StandardKernel(new SiteModule());
}
}
class SiteModule : NinjectModule
{
public override void Load()
{
Bind<ILogger>().To<NLogger>().InSingletonScope();
}
}
</script>
As you didnt rule it out in your question, I have to assume you're not aware of the WebForms equivalent of the one you cited
(Linked from the Ninject extensions index on the home site)