简体   繁体   English

从C#(.Net 3.5)页面导航时调用方法的方法?

[英]Way to call a method when navigating away from a page in C# (.Net 3.5)?

I am working on a project such that once a user is directed to a certain page, they receive a certain level of "authentication" and I wanted to remove this "authentication" if the user tried to navigate away from the page before they completed a form. 我正在做一个项目,以便一旦将用户定向到某个页面,他们就会收到一定级别的“身份验证”,并且如果用户在完成操作之前试图离开页面,则我想删除此“身份验证”形成。

I was wondering if the is a way to get a method to call when redirecting away from a specific page that fit into the Page event life cycle (or a different one if you have suggestions)? 我想知道从重定向到适合Page事件生命周期的特定页面(如果有建议的话,则从另一个页面)重定向时,是否是一种方法来调用?

I am kind of new to C# and the .Net framework, so if this is not standard, then just tell me what would be the correct approach for this. 我是C#和.Net框架的新手,所以,如果这不是标准的,那么请告诉我什么是正确的方法。

Thanks! 谢谢!

You could try using a PageMethod triggered by a JavaScript event. 您可以尝试使用由JavaScript事件触发的PageMethod。 This needs a ScriptManager in the aspx. 这需要在aspx中使用ScriptManager。

Example: JavaScript 示例:JavaScript

function LeavePage(e) {
    PageMethods.RevokeAuthentication();
}

window.onbeforeunload = LeavePage;

C# Code behind 后面的C#代码

[PageMethod]
public static void RevokeAuthentication()
{
    // Do stuff here
}

However, this method is not foolproof. 但是,此方法并非万无一失。 If the client's browser has scripting disabled the JavaScript will not run. 如果客户端的浏览器已禁用脚本,则JavaScript将不会运行。

Perhaps a better method is to handle the authentication in a MasterPage with a Session. 也许更好的方法是使用Session在MasterPage中处理身份验证。 A MasterPage is similar to how PHP developers use includes. MasterPage与PHP开发人员使用include的方式相似。

Eg OnLoad check page, if pageName allowed higher authentication, set it, else revoke it. 例如OnLoad检查页面,如果pageName允许更高的身份验证,请对其进行设置,否则将其撤销。

Your page will not know it is being navigated away from as it is effectively stateless. 您的页面实际上是无状态的,因此不会知道该页面正在离开。 Once the page is generated by the C#, it is transmitted to the browser. 页面由C#生成后,便被传输到浏览器。 The page does not "live" in the C#. 该页面不在C#中“活动”。 Once generated, that's it. 一旦生成,就是这样。

You could use a session variable to track the user's "authentication" level. 您可以使用会话变量来跟踪用户的“身份验证”级别。 If they hit other pages, you can check the value of this variable and act accordingly. 如果它们到达其他页面,则可以检查此变量的值并采取相应措施。 If they complete the form, you record that fact in the session. 如果他们填写了表格,则可以在会话中记录该事实。

Another option would be to use javascript to callback to the server when the user is leaving the page. 另一种选择是在用户离开页面时使用javascript回调到服务器。 This wouldn't act within the Page event life cycle as it will already be complete 这不会在Page事件生命周期内起作用,因为它已经完成了

Does this "authentication" exist for long? 这种“身份验证”是否存在很长时间? Do you need to persist it? 您需要坚持吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM