Setting Page Async mode to true from Code-Behind

三世轮回 提交于 2019-12-20 02:53:28

问题


Is it possible within my code-behind file to set the asynchronous mode of the page directive.

I have no way of directly modifying the <%@Page %> attribute and and struggling to find a way to implement this in my code-behind.

I have tried in my Page_Load method to add Page.AsyncMode = true, but it returns the following error:

is inaccessible due to its protection level

Is there any way to do this? Without being able to directly modify the master page?


回答1:


No, you cannot change the asynchronous mode of a page in the code-behind. An asynchronous page implements the IHttpAsyncHandler interface, and there is no way to change the interfaces implemented by your page after the .aspx file has been compiled by ASP.NET and your code is running.

Setting the Page.AsyncMode property will not change the asynchronous mode. Its purpose is to let controls on the page know whether the page is running in asynchronous mode or not, so tampering with the property may cause controls to malfunction.




回答2:


My guess - you're trying to access this property from your master page. But according to documentation, this property is protected bool AsyncMode { get; set; }. Which means it is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

This property is declared in System.Web.UI.Page and is accessible in it and any class derived from it. MasterPage doesn't derive from Page. That's why you cannot access it.

You can easily access it from your page:

public partial class YourPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.AsyncMode = true;
    }
}



回答3:


Because you're MasterPage does not Inherit from your Page, you cannot access the AsyncMode Property.

If you absolutely must edit the value from your MasterPage maybe consider adding a method to your page called "UpdateAsyncMode" and doing the following from your masterpage Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        MyPageClass p = this.Page as MyPageClass ;

        p.UpdateAsyncMode(true);
    }

Alternatively if this is something that needs to be more robust you could create a base class for Pages like the following and have all the web pages in your site extend that base class

public abstract class MyBasePage : System.Web.UI.Page
{
    public void UpdateAsyncMode (bool b)
    {
        this.AsyncMode = b;
    }
}


来源:https://stackoverflow.com/questions/9094574/setting-page-async-mode-to-true-from-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!