gpt4 book ai didi

c# - 用于 Web 应用程序的 GetEntryAssembly

转载 作者:IT王子 更新时间:2023-10-29 03:55:32 27 4
gpt4 key购买 nike

Assembly.GetEntryAssembly() 不适用于网络应用程序。

但是……我真的需要这样的东西。我使用一些在 Web 和非 Web 应用程序中使用的深层嵌套代码。

我目前的解决方案是浏览 StackTrace 以找到第一个调用的程序集。

/// <summary>
/// Version of 'GetEntryAssembly' that works with web applications
/// </summary>
/// <returns>The entry assembly, or the first called assembly in a web application</returns>
public static Assembly GetEntyAssembly()
{
// get the entry assembly
var result = Assembly.GetEntryAssembly();

// if none (ex: web application)
if (result == null)
{
// current method
MethodBase methodCurrent = null;
// number of frames to skip
int framestoSkip = 1;


// loop until we cannot got further in the stacktrace
do
{
// get the stack frame, skipping the given number of frames
StackFrame stackFrame = new StackFrame(framestoSkip);
// get the method
methodCurrent = stackFrame.GetMethod();
// if found
if ((methodCurrent != null)
// and if that method is not excluded from the stack trace
&& (methodCurrent.GetAttribute<ExcludeFromStackTraceAttribute>(false) == null))
{
// get its type
var typeCurrent = methodCurrent.DeclaringType;
// if valid
if (typeCurrent != typeof (RuntimeMethodHandle))
{
// get its assembly
var assembly = typeCurrent.Assembly;

// if valid
if (!assembly.GlobalAssemblyCache
&& !assembly.IsDynamic
&& (assembly.GetAttribute<System.CodeDom.Compiler.GeneratedCodeAttribute>() == null))
{
// then we found a valid assembly, get it as a candidate
result = assembly;
}
}
}

// increase number of frames to skip
framestoSkip++;
} // while we have a working method
while (methodCurrent != null);
}
return result;
}

为了确保程序集是我们想要的,我们有 3 个条件:

  • 程序集不在 GAC 中
  • 程序集不是动态的
  • 不生成程序集(以避免临时的 asp.net 文件

我遇到的最后一个问题是基页是在单独的程序集中定义的。(我使用 ASP.Net MVC,但它与 ASP.Net 相同)。在这种特殊情况下,返回的是单独的程序集,而不是包含页面的程序集。

我现在要找的是:

1) 我的装配验证条件是否足够? (我可能忘记案例了)

2) 有没有办法从 ASP.Net 临时文件夹中给定的代码生成的程序集中获取有关包含该 Page/View 的项目的信息?(我想不是,但谁知道呢……)

最佳答案

这似乎是获取 Web 应用程序“入口”或主程序集的可靠、简单的方法。

如果您将 Controller 放在一个单独的项目中,您可能会发现 ApplicationInstance 的基类与包含 View 的 MVC 项目不在同一个程序集中 - 但是,这种设置似乎很少见(我提到它是因为我'我曾经尝试过这种设置,不久前有几个博客支持这个想法)。

    static private Assembly GetWebEntryAssembly()
{
if (System.Web.HttpContext.Current == null ||
System.Web.HttpContext.Current.ApplicationInstance == null)
{
return null;
}

var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP") {
type = type.BaseType;
}

return type == null ? null : type.Assembly;
}

关于c# - 用于 Web 应用程序的 GetEntryAssembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com