ASP.NET网站发布不会重新编译codebehind。
创始人
2024-09-19 12:30:22
0

在ASP.NET网站中,如果更改了codebehind文件的代码,通常需要重新编译整个网站以使更改生效。然而,有一种解决方法是使用动态编译来实现在不重新编译整个网站的情况下更新codebehind文件的代码。

以下是一个示例,演示如何使用动态编译来实现这一点:

  1. 首先,确保在Web.config文件中启用了动态编译。在 节点下添加以下代码:

  1. 在你的ASP.NET页面的CodeBehind文件中,添加以下代码:
private void Page_Init(object sender, EventArgs e)
{
    // 检查是否存在编译错误
    if (HttpContext.Current.Application["CompilationError"] != null)
    {
        // 如果存在编译错误,抛出异常并显示错误信息
        throw new Exception((string)HttpContext.Current.Application["CompilationError"]);
    }
}

private void Page_Load(object sender, EventArgs e)
{
    // 在页面加载时,动态编译codebehind文件
    CompileCodeBehind();
}

private void CompileCodeBehind()
{
    // 获取当前页面的类型
    Type pageType = this.GetType();

    // 获取当前页面的文件路径
    string pageFilePath = this.AppRelativeVirtualPath.Replace("~", "");

    // 创建编译器参数
    CompilerParameters compilerParams = new CompilerParameters();
    compilerParams.GenerateInMemory = true;
    compilerParams.IncludeDebugInformation = true;
    compilerParams.ReferencedAssemblies.Add("System.dll");

    // 获取当前页面的代码
    string codeBehindCode = File.ReadAllText(Server.MapPath(pageFilePath));

    // 创建C#代码提供程序
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();

    // 编译codebehind文件
    CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParams, codeBehindCode);

    // 检查是否有编译错误
    if (compilerResults.Errors.HasErrors)
    {
        // 如果有错误,将错误信息存储在Application对象中,以便在下一次加载页面时抛出异常
        string errorMessage = "";
        foreach (CompilerError error in compilerResults.Errors)
        {
            errorMessage += error.ErrorText + "\n";
        }
        HttpContext.Current.Application["CompilationError"] = errorMessage;
    }
    else
    {
        // 如果编译成功,将新编译的程序集加载到AppDomain中
        Assembly compiledAssembly = compilerResults.CompiledAssembly;
        HttpRuntime.CodegenDir = compiledAssembly.CodeBase;
    }
}
  1. 在你的ASP.NET页面中,添加以下代码:
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    Page.Init += Page_Init;
    Page.Load += Page_Load;
}

这样,每当页面被加载时,都会检查是否有编译错误,并且如果没有错误,将会动态编译codebehind文件。如果有编译错误,则会抛出异常并显示错误信息。

请注意,这只是一个简单的示例,实际使用中可能需要根据自己的需求进行一些修改。此外,动态编译也可能会带来一些性能开销,因此请谨慎使用。

相关内容

热门资讯

透视黑科技!wpk控制牌是真的... 透视黑科技!wpk控制牌是真的吗,wpk有作弊吗(透视)原先真的有挂(详细教程)1、每一步都需要思考...
透视肯定!约局吧辅助器,pok... 透视肯定!约局吧辅助器,pokemmo脚本最新版,切实真的是有挂(可靠教程)1、pokemmo脚本最...
透视辅助!佛手大菠萝有挂吗,w... 透视辅助!佛手大菠萝有挂吗,wpk辅助器(透视)果然真的是有挂(2025新版教程)小薇(透视辅助)致...
透视线上!pokermaste... 透视线上!pokermaster脚本,来玩app 德州 辅助,都是存在有挂(新2025教程)1、透视...
透视app!如何下载wepok... 透视app!如何下载wepoker安装包,wepoker有没有插件(透视)往昔存在有挂(曝光教程)1...
透视教程!菠萝辅助器免费版的特... 透视教程!菠萝辅助器免费版的特点,德州圈脚本,切实真的有挂(揭秘攻略);1、菠萝辅助器免费版的特点a...
透视挂透视!wepoker透视... 透视挂透视!wepoker透视器免费,wepoker好友房开挂(透视)往昔有挂(AI教程)1、wep...
透视模拟器!pokerrrr2... 透视模拟器!pokerrrr2辅助,newpoker怎么安装脚本,确实是真的有挂(总结教程)1、全新...
透视私人局!扑克之星辅助,德州... 透视私人局!扑克之星辅助,德州hhpoker脚本(透视)确实真的有挂(攻略教程)1、在德州hhpok...
透视计算!pokermaste... 透视计算!pokermaster修改器,拱趴大菠萝挂哪里,一直存在有挂(分享教程);1、完成拱趴大菠...