Intercepting asp.net ajax webmethod - asp.net

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.

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"] + "";
}
}

ASP.NET initialization of array

I have website with array (list) of 1000 objects, these objects are loading from json to array every website refresh. I would like to load these objects from json to array only once and keep it in RAM for others users. Because everytime read file is much slower than read it from RAM.
I am using ASP.NET Web Forms
How is it posssible?
I would recommend to define the array as an static member of a class and then initialize it with help of Global.asax, use the Application_Start event handler.
to add Global.asax to you project in Visual Studio:
File -> New -> File -> Global Application Class
Here is a sample C# code for Global.asax.cs:
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// ... Your initialization of the array done here ...
}
protected void Session_Start(object sender, EventArgs e)
{
}
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)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
Are these values static, i.e., do they stay constant while your application is running? In that case, the easiest way is to cache those values.
You can use static variables for that, but the recommended way is to use the thread-safe Cache object provided by ASP.NET. It can be accessed with the Cache property of the Page or of the HttpContext.
Example:
var myList = (MyListType)Cache["MyList"];
if (myList == null)
{
myList = ...; // Load the list
Cache["MyList"] = myList; // Store it, so we don't need to load it again next time.
}
Further reading:
Caching Application Data

WCF\ASP.NET interoperability

I have a server application written in WCF using asynchronous callbacks, and a webforms application in ASP.NET.
All of the communication is fine between the 2 applications, I can call the exposed functions in the server via the web application, and the server can send callbacks to the web application, however sometimes the functions within the callback work, and other times, they don't.
For example, I would like a login button on the web app to send a username and password to the server, the server checks this against the database, and if the login information is correct, it should send a callback, which opens a new page in the web app.
Here is the relevant server code:
public void Login(String username, String password)
{
//DoCheckAgainstDatabase(username, password);
ICallback callback = OperationContext.Current.GetCallbackChannel<ICallback>();
callback.LoginSuccess();
}
and the web application code:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
I can put in breakpoints, and see that everything is working fine, it's just that the code 'ScriptManager.RegisterStartupScript...' does not execute properly all the time.
Could this be something to do with threading? Could anyone suggest a way to fix this please?
Thanks in advance!
David
It occurs to me that it's possible your page life cycle may be ending - or at least getting to the Render stage, which is where the start up script would be written to the output - before the callback is called.
Is it possible to call your service synchronously, and not proceed out of LoginButton_Click until the service call returns?
I think you are missing script tag - wrap your window.oppen with it, like
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "<script>window.open('Client.aspx','_self');</script>", true);
Thank you Ann L. for guidance on this. I have added a ManualResetEvent, and then in the button click method, I wait until I have received the callback, then proceed with opening the new page:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
_resetEvent.WaitOne();
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
_resetEvent.Set();
}

Cookie does not work in asp.net

I have two pages, test1.aspx and test2.aspx
test1.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test", "test");
cookie.Expires = DateTime.Now.AddDays(1);
Response.SetCookie(cookie);
}
test2.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Response.Cookies["test"].Value);
}
The value of the cookie is null, no matter how many times I tried. I tried to open page1 and then page 2, expecting a cookie to work, but it is not working, I don't know why.
I think you need to read off the Request instead of the response.
As MSDN suggestions
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
In a web application, the request comes from the client (browser) and the response is sent from the server. When validating cookies or cookie data from the browser you should use the Request.Cookies collection. When you are constructing cookies to be sent to the browser you need to add them to the Response.Cookies collection.
Additional thoughts on the use of SetCookie
Interestingly for HttpResponse.SetCookie as used on your first page; MSDN says this method is not intended for use in your code.
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Even the example code found on this page uses the Response.Cookies.Add(MyCookie) approach and does not call SetCookie
You need is :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
There is a sample here:
Reading and Writing Cookies in ASP.NET and C#
Regards
Save cookie with (response) and read cookie by (request)
//write
response.cookies("abc") = 123;
//read
if ((request.cookies("abc") != null)) {
string abc = request.cookies("abc");
}
Use Response.Cookies.Add(cookie);
Reference: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies
On page test2.aspx
You should try this
protected void Page_Load(object sender, EventArgs e)
{
var httpCookie = Request.Cookies["test"];
if (httpCookie != null)
{
Response.Write(httpCookie.Value);
}
}

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.

Resources