Intercept session variable in ASP.NET (translation)

xiaoxiao2021-03-06  107

Intercepting session variables in ASP.NET

/ / ====================================================================================================================================

Author Information: Robbe Morris is a 2004Microsoft MVP (Visual C #) and senior software engineer. He is an engineer of Eggheadcafe.com, eggheadcafe.com support website development engineers.

(Note: This question did not have the original author to agree, I only use it for learning, if you have any inconvenience, please forgive me.

Original address: http://www.eggheadcafe.com/articles/hijacksession.asp

/ / ================================ 蠢 的 用户! I call me like this. Those users can't get through those things that you tell him to get what he works and life, the website cannot complete such a job. As we all know, this is a fact. Can see what they entered and as close as possible to the situation where they look good! Today is often my mother give us more inspiration, how is it funny! Things often happen to a new feature, use the module to intercept HTTP requests, for tracking a page that browsing users who are often questioned by users (I will be briefly description) in a double repair day After the repair, I proposed a prototype or in fact a program that changed as little as possible on an existing website. The encoding technology that intercepts HTTP requests has been mentioned by many technical guidelines and programming books. Therefore, I will not use the basic knowledge to bother you, there is a connection from MSDN to us to use: "In ASP.NET. Perform security request processing, filtering, and content orientation" with HTTP pipes. Our goal is to find a technique that allows technical support to intake or intercepting user session variables and automatic sending technical support pages to the last page used by users. Maybe we don't need to find which user and their login information or ask many questions about where they are on the website, how do they reach the problem. How did they go there. If you have already listened to technical support you, you know how difficult users and technical support are frustrated. Second goals, he will help technical support the real time that can monitor form elements. Finally, but not the smallest, implementing this solution does not change the existing website. Also make it possible to span multiple sites. This is prepared for a product order program. This is the purpose of this article. I will keep a brief summary in a nutshell, how did he work? The code example consists of an ASP.NET program called TechSupport, and a set of iiscapture assemblies .Techsupport is just a DEMO, and the example contains 6 lines of code into two pages to implement this program. The three lines of code in the first page are in askforhelp.asp. It creates a new questionnaire in the current program, saving the current session information in cache, CACH saves the last page of the problem entry information and the last page of the user access to this user as a technical support model, set a reasonable The expiration date is in this cache so that it will not disappear in memory.

When the user has another request page, the technical support mode will allow us to transfer from one element value and anything else to our technical support is useful for our technical support to the updated session value, // ======= =========================================== askFORHELP.ASPX String URL = Request.QueryString ["Techsupporturl"]. Tostring (); IiScapture.TroubleticTicket odicket = new iiScapture.troubletic (); mssessionkey = oticket.loadnewsessionToApplication (System.Web.httpContext.current, URL); // ================ =============================== The second is the page that technical supports themselves. In the same example, technical support requires a simple licking, and there is a problematic entry number then submitted. From here, we will discover user session data with problems, repeat these values ​​from one element data and any other program cache, to view them to technical support. Then, they are directed to the page that the user is finally logged in. Perhaps your product program's solution should include more security tests to facilitate technical support for recording error messages.

/ / =========================================================================================================================================================================================== =================== techsupportlogin.aspx IISCapture.TroubleTicket oTicket = new IISCapture.TroubleTicket (); oTicket.LoadSessionFromApplication (System.Web.HttpContext.Current, this.TextBox1. Text); oticket.transfertourl (System.Web.httpContext.current); // ================================= ================================================================================================================================================== new. We add a HyperLink management in all sites that all logic happen to the external Iiscapture program set, which can intercept HTTP requests. The TroubleticTicket class's operational data and the LOG class process blocks the HTTP request. After a glimpse, you may think this solution cannot work in a web farm environment. This is incomplete correctly iiscapture.troubleticketicket.LoadSession can be modified to save the IP address of the server in the executed URL to take the domain name. Once you use sessions (forced every part of each concurrent page request), technical support to log in to the same service (in your program, you can decide when to terminate and contain a landing connection), if you don't have to choose, then Save Objects in a database into byte arrays, which is better to save this in this article. Let us first discuss the user request before reading the source code Log and TroubleticTicket class 1. Analyze the user's Web trail four months ago, you have built a website, you receive a request, what is the request to report what is your website? , Access page, what page. Naturally, when this demand begins to the last deadline, they say it is not necessary, because you have not traced your own traces. In fact, you can simply add an HTTP Module to intercept the page request and write him into a centralized database. If you have included a user ID in the Session variable or hide it in the form You can extract these requests to write into the log; if not, add some code in your login store to save userid and sessionID One table in the database.

You can add the sessionid of the landing page to your userid. In short, minimize change, it is necessary for your website, and we have already implemented your request. 2. Free change Outputs My code in FilterHTML, you can view. With FilterHTML override the Response.filter class in the ReleaseRequestState event in the LOG class. The FilterHTML Class class is available in the Filter.html.Write method overrides Response.filter.write and allows you to modify the output to the browser. Note The note is why this may have many reasons, you want to improve the stream. One makes me noticed that it is a safety reason. As a prevention of hackers, you can write a query in the output stream to see if there is any dangerous information about your website, database server, or other different form hackers may take the attack marks such as SQL injection attack, malicious format request, etc. Wait. The current website is prone to various types of attacks. This should be a importerHtml class that you should clean up code blocking these gaps can be adjusted to pass a REF string. Return to HTML Stream, and the program sent to the browser The FilterHTML class passes a REFREF string that can be returned to the HTML stream sent to the browser, monitor what is sent to the client. 3. Pass to the sessions value to other sites you can use Server.Transfers to deceive other sites you operate. When entering or leaving this site, an HTTP intercept module exists in sites a, b can work simultaneously. If a change is found, in a concentrated place, such as a database capture and save this session data, create a unique entry and increase him In the URL, execute, server.transfer is transferred to the target page When the site b waits for this request, he calls a response.Redirect to a target page with the session value and minus the entry tag in the URL. When you are taking this example, make sure you have read the description of AskForhelp.aspx, you can start pointing from Ebform1.aspx, registering your favorite name Button Send your registration information to Webform2.aspx, where you can Point Technical Support Connection Take a new window to open, it points to a problematic user entry. Copy / Paste the URL to the new window, the browser will display the page as a technical support to set a different short bit in the method body, and you can see the program is running. Let's take a look at the log and trunketic class. How do they work? Log.cs using system; use system.web; use system.web.sessionState; use system.data.sqlclient; use system.diagnostics; using system.collections; using System.Collections.Specialized; using System.IO; using System.Text; namespace IISCapture {public class Log: IHttpModule {HttpApplication HttpApp; HttpRequest HttpReq; HttpResponse HttpRes; public void Init (HttpApplication App) {// First event in the event Chain app.beginRequest = new eventhandler (onbeginRequest);

// Session state for the request is not available until this event fires App.AcquireRequestState = new EventHandler (AcquireRequestState);. // If you want to alter the output stream on the fly, do it here App.ReleaseRequestState =. New EventHandler (ReleaseRequestState);

} // Application Context Events

private void OnBeginRequest (object sender, EventArgs eventArgs) {HttpApp = (HttpApplication) sender; HttpReq = HttpApp.Context.Request; HttpRes = HttpApp.Context.Response; try {} catch (Exception err) {ProcessError (err.Message); }

private void AcquireRequestState (object sender, EventArgs eventArgs) {string Ticket = ""; string Url = ""; try {// Reload application cache with the user's session info and // also grab the last posted form elements and their values ​​if. (this.IsSessionInTechSupportMode () == true) {IISCapture.TroubleTicket oTicket = new IISCapture.TroubleTicket (); Ticket = HttpApp.Context.Session [IISCapture.TroubleTicket.TechSupportKey] .ToString (); Url = HttpApp.Context.Session [ IISCapture.TroubleTicket.TechSupportUserLastPage] .ToString (); oTicket.LoadSessionToApplication (HttpApp.Context, Ticket, Url); oTicket.LoadFormToApplication (HttpApp.Context, Ticket); return;}

// get the problem user's session info again if (this.IsSessionATechSupportRep () == true) {IISCapture.TroubleTicket oTicket = new IISCapture.TroubleTicket ();. Ticket = HttpApp.Context.Session [IISCapture.TroubleTicket.TechSupportKey] .ToString (); Oticket.loadsessionFromapplication (httpapp.context, ticket); // Here is a sample of how to read the posted form value from the user // needing technical support: try {

Object [,] ovalues ​​= oticket.getformfromapplication (httpapp.context, ticket); for (int i = 0; i <= ovalues.getupperbound (1); i ) {debug.write (Ovalues ​​[0, i] .tostring ) ":"); Debug.writeline (Ovalues ​​[1, i] .tostring ());

} CatCh {}}

} CatCH (Exception Err) {processerror (err.message);}}

private void ReleaseRequestState (object sender, EventArgs eventArgs) {// This event is a good choice for apply filters to the output // stream to the browser / client. By overriding the filter, you // can modify the output stream after all the response.write's are // done and before it gets to the browser. // Just add your own business rules to determine whether a filter // should be applied at all. try {if (HttpRes.ContentType! = "text / html" ) {return;} // httpres.filter = new iiscapture.FilterHTML (Ref CaptureSession, httpres.filter);} catch (exception err) {processerror (err.message);}}

// Custom Methods

private bool IsSessionInTechSupportMode () {bool Ret = false; try {if (! HttpApp.Context.Session [IISCapture.TroubleTicket.TechSupportEnable] = null) {if (HttpApp.Context.Session [IISCapture.TroubleTicket.TechSupportEnable] .ToString () == "1") {Ret = true;}}} catch {} return Ret;} private bool IsSessionATechSupportRep () {bool Ret = false; try {if (HttpApp.Context.Session [IISCapture.TroubleTicket.TechSupportRep] =! NULL) {if (httpapp.context.session [iiScapture.toubletic.techsupportrep] .tostring () == "1") {RET = true;}}} cat}}

Private void processerror (string errmsg) {httpapp.context.response.write (errmsg);

Public void dispose () {}}}

Troubleticket.cs using system; using system.collection; using system.ipe; using system.diagnostics;

namespace IISCapture {public class TroubleTicket {public const string TechSupportUserLastPage = "TechSupportUserLastPage"; public const string TechSupportEnable = "TechSupportEnable"; public const string TechSupportKey = "TechSupportKey"; public const string TechSupportRep = "TechSupportRep"; public const string TechSupportCache = "TechSupportCache_ "; Public const string techsupportcachesession =" session_ "; public const string techsupportcacheform =" form_ ";

Public Troubleticket () {}

public void TransferToUrl (HttpContext oContext) {try {oContext.Response.Redirect (oContext.Session [TechSupportUserLastPage] .ToString ());} catch (Exception) {throw;}} public string LoadNewSessionToApplication (HttpContext oContext, string GotoUrl) {string TroubleTicket = ""; try {TroubleTicket = System.Guid.NewGuid () ToString ();. LoadSessionToApplication (oContext, TroubleTicket, GotoUrl); LoadFormToApplication (oContext, TroubleTicket);} catch (Exception) {throw;} return TroubleTicket;} public void LoadSessionToApplication (HttpContext oContext, string TroubleTicket, string GotoUrl) {try {oContext.Session [TechSupportUserLastPage] = GotoUrl; oContext.Session [TechSupportKey] = TroubleTicket; object [,] oValues ​​= new object [2, oContext.Session.Keys .Count];

For (int i = 0; i

OconText.Session [Techsupportenable] = "1";

if ((object [,]) oContext.Cache [TechSupportCache TechSupportCacheSession TroubleTicket.Trim ()] = null!) {oContext.Cache.Remove (TechSupportCache TechSupportCacheSession TroubleTicket.Trim ());}

oContext.Cache.Insert (TechSupportCache TechSupportCacheSession TroubleTicket, _ oValues, null, DateTime.MaxValue, TimeSpan.FromMinutes (10));} catch (Exception) {throw;} return;} public void LoadFormToApplication (HttpContext oContext, string TroubleTicket ) {BOOL FOUND = FALSE; Try {Object [,] ovalues ​​= new object [2, OconText.Request.form.keys.count]; for (int i = 0; i

oContext.Cache.Insert (TechSupportCache TechSupportCacheForm _ TroubleTicket, oValues, null, DateTime.MaxValue, TimeSpan.FromMinutes (10));} catch (Exception) {throw;} return;} public string LoadSessionFromApplication (HttpContext oContext, string TroubleTicket ) {String gotourl = ""

Try {Object [,] ovalues ​​= (Object [,]) Ocontext.cache [TechsupportCache _ TechsupportCacheSession TroubleticketTicket.trim ()]; for (int i = 0; i <= ovalues.getupperbound (1); i ) { Ocontext.Session [Ovalues ​​[0, I] .tostring ()] = Ovalues ​​[1, i];

oContext.Session [TechSupportEnable] = "0"; oContext.Session [TechSupportRep] = "1"; GotoUrl = oContext.Session [TechSupportUserLastPage] .ToString ();} catch (Exception) {throw;} return GotoUrl;} public object [,] GetFormFromApplication (HttpContext oContext, string TroubleTicket) {object [,] oValues ​​= null; try {oValues ​​= (object [,]) oContext.Cache [TechSupportCache TechSupportCacheForm TroubleTicket.Trim ()];} catch (Exception) {throw;}}}}

转载请注明原文地址:https://www.9cbs.com/read-123645.html

New Post(0)