CSRF synchronize token pattern implementation in ASP.net webform app - asp.net

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);
}
}

Related

How to hide a div which is in master page using asp.net?

Iam tried to hide a div which is placed in master page,but i got an error like this "Object reference not set to an instance of an object".
My codes
<div runat="server" id="cnms">
Cinemas
</div>
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AdminMaster admns = new AdminMaster();//This si my admin page
admns.FindControl("cnms").Visible = false;//I got error here
}
}
What went wrong for me?any solution?
The approach you are using is instantiating a new instance of the masterpage, which when you do that it all of the control references are null. You need to use the existing master page instance, using the Page.Master property like the following:
protected void Page_Load(object sender, EventArgs e)
{
AdminMaster admns = (AdminMaster)Page.Master; //This si my admin page
admns.FindControl("cnms").Visible = false;//I got error here
}

UserControl has IsPostBack, but Control does not

i'm trying to solve a bug in Visual Studio, the suggestion is to stop using UserControls and use Control instead..
So i'm converting all my UserControl into just Control, e.g.:
public partial class Controls_UserManagement_GroupManager : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
becomes
public partial class Controls_UserManagement_GroupManager : System.Web.UI.Control
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Except that there is no Control.IsPostBack?
How do i replace UserControl with Control?
Series
This question is one in the ongoing Stackoverflow series, "Templating user controls":
How to add a Templating to a UserControl?
How to inherit from Control, rather than UserControl?
UserControl has IsPostBack, but Control does not
UserControl does not have public property named ContentTemplate
How do i specify CodeFileBaseClass from web.config?
Control has a Page property, which has an IsPostback property. This should give you the value you need.
public class MyControl : Control{
protected override void OnInit( EventArgs e ){
if( this.Page.IsPostBack ){
// do something
}
}
}
MSDN Reference

Routing and Ninject gives 404

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);
}

ASP.NET: Get Page's filename

I have an ASPX page named Default.aspx. From its codebehind on Page_Load(), I would like to get "Default.aspx", alone, into a string:
protected void Page_Load(object sender, EventArgs e)
{
string aspxFileName = ?;
}
What should I replace ? with—what will get me the ASPX filename?
System.IO.Path.GetFileName(Request.PhysicalPath);
protected void Page_Load(object sender, EventArgs e)
{
string cssFileName = Path.GetFileName(this.Request.PhysicalPath).Replace(".aspx", ".css");
}
Some short answers are already taken so, for fun, and because you'll likely want to do this from other Web Forms, here's an expanded solution that will affect all Web Forms in your project uniformly (includes code to get a filename as requested).
Make an extension method for the System.Web.UI.Page class by putting this code in a file. You need to use .NET 3.5.
namespace MyExtensions {
using System.Web.UI;
static public class Extensions {
/* You can stuff anybody else's logic into this
* method to get the page filename, whichever implementation you prefer.
*/
static public string GetFilename(this Page p) {
// Extract filename.
return p.AppRelativeVirtualPath.Substring(
p.AppRelativeVirtualPath.IndexOf("/") + 1
);
}
}
}
To get the filename from any ASP.NET Web Form (for example in the load method you specified):
using MyExtensions;
protected void Page_Load(object sender, EventArgs e) {
string aspxFileName = this.GetFilename();
}
Call this method on any Web Form in your project.

Pass MasterPage ImageButton event to content Page

I have ImageButton in a MasterPage. I want the OnClick event to fire and be captured by the .ASPX page hosted inside the MasterPage?
MasterPage:
<asp:ImageButton ID="btnClear" OnClick="Clear_Click"
ImageUrl="images/Back_Icon_06.png" runat="server" AlternateText="Clear"
width="38" height="39"/>
The masterpage is actually a child of the page (in fact, it's a UserControl). We don't want the page to have to be aware of the intimate details of its child controls (thats why we delegate those aspects to those controls in the first place), so the correct approach would be to handle the click event on the master page and from there fire another event on the masterpage which the page handles:
Master:
public event EventHandler SomethingHappened;
protected void Button_Click(object sender, EventArgs e)
{
OnSomethingHappened(EventArgs.Empty);
}
protected void OnSomethingHappened(EventArgs e)
{
if(this.SomethingHappened != null)
{
this.SomethingHappened(this, e);
}
}
Page:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//allows us to change master pages
if(this.Master is MyMaster)
{
((MyMaster)this.Master).SomethingHappened += new EventHandler(HandleSomethingHappened);
}
}
private void HandleSomethingHappened(object sender, EventArgs e)
{
//deal with it
}
I would recommend specifying a strongly typed master page in your content page and exposing the event on the master page side
Here's a good MSDN reference
This is similar to what Rex M specified but just simplifies accessing the Master Page a little bit.
// Master Page Code
public event EventHandler ClearClick
{
add
{
this.btnClear.Click += value;
}
remove
{
this.btnClear.Click -= value;
}
}
// Content Page markup
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
// Content Page Code
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Master.ClearClick += new EventHandler(OnClearClick);
}
private void OnClearClick(object sender, EventArgs e)
{
// Handle click here
}

Resources