ASP.NET: Get Page's filename - asp.net

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.

Related

How to simulate MVC routing in WebForm ASP.Net?

You all have seen how MVC minifies URL by default in form of url: "{controller}/{action}/{id}". It's done in RouteConfig.cs.
I'm looking for a way so that a webform URL like mywebsite.com/Page/Default.aspx?id=100&Browser=ff changes to mywebsite.com/Page/Default/100?Browser=ff, It should be done in Globa.ascx.
There are some posts in StackOverFlow website which instructs how to redirect a reserved URL to a certain page, it's obvious that my question is something else, I'm looking for a way to offer a pattern in Global.ascx.
At the solution explorer, under your project, add a new ASP.NET item "Global.asax"
Add the using statement:
using System.Web.Routing;
At the Application_Start event, type in your routing URL, for example:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("default1", "Page/Default", "~/Page/Default.aspx");
RouteTable.Routes.MapPageRoute("default2", "Page/Default/{controller}/{action}/{id}", "~/Page/Default.aspx");
}
Then, at the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string controller = RouteData.Values["controller"] + "";
string action = RouteData.Values["action"] + "";
string id = RouteData.Values["id"] + "";
}
}

CSRF synchronize token pattern implementation in ASP.net webform app

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

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

Intercepting asp.net ajax webmethod

Is there a way to intercept asp.net ajax webmethods(aspx page static methods)?
i want to intercept before request reaching the method and also after sending the response.
use in global.asax file
protected void Application_BeginRequest(Object sender, EventArgs e)
{
//before method colling
string ss = HttpContext.Current.Request.Url.ToString();//use if it is equal to your page webmethod url i.e. domain.com/dfault.aspx/GetMessage;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
//after method colling
string ss = HttpContext.Current.Request.Url.ToString();// use if it is equal to your page webmethod i.e. domain.com/dfault.aspx/GetMessage;;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
you can try fiddler or HTTtamper.

How to use URL Re-Write with Query String

I am trying to create a URL re-write with a query string but my problem is the URL re-write does not work when I try to use the query string. The URL re-write works fine when I use it without the query sting. I have searched online and did exactly what they said but I was still getting an error. So let me show you what works first which is without the query-string:
This is what I have in the Global.asax file:
protected void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteForCustomer", "MyTest", "~/Users/MyOldPage.aspx");
}
Everything works fine if I run the code above.
So I have tried now to pass query-string in the URL and this what I have done that does not work so far:
protected void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteForCustomer", "MyTest/{My_ID}", "~/Users/MyOldPage.aspx");
}
And the code behind for MyOldPage.aspx I have this code but not sure if it is even necessary but this is what I saw online when I was researching:
protected void Page_Load(object sender, EventArgs e)
{
string myquerystring = Page.RouteData.Values["My_ID"] as string;

Resources