c# - 共享程序集中属性的 TypeLoadException

标签 c# .net asp.net-web-api attributes

11 月 7 日 10:29 MST 更新

奇怪的是,如果我将属性从 ComponentModel 文件夹中移回 Common 项目的根目录,代码就可以正常工作。在为 InflowHealth.Common.ComponentModel 命名空间重构所有引用之后,我无法想象什么可能引用旧命名空间。

这几乎就像有一些引用隐藏在某个地方,而不是基于代码,而是运行时和动态的,但我在查看 InflowHealthErrorContext 的所有查找结果时肯定没有看到它。

11 月 6 日 19:33 MST 更新

有趣的是,当我注释掉使用自定义属性继承路由并使用默认属性的行时,它仍然爆炸了。更有意思的是,它正在寻找的命名空间>.

11 月 6 日 07:42 MST 更新

我相信我已经确定问题与我用来继承操作的另一个自定义属性有关。此属性添加到 HttpConfiguration 中,如下所示:

public static void MapInheritedAttributeRoutes(this HttpConfiguration config)
{
    config.MapHttpAttributeRoutes(new InheritanceDirectRouteProvider());
}

该属性的实现非常简单:

public class InheritanceDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
    {
        return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(true);
    }
}

继承此 InflowHealthErrorContext 属性似乎导致了问题,但我不确定到底是什么问题。我试过:

  • 删除 Inherited = false,使其可继承。
  • 删除 AllowMultiple = true 只是因为配置错误。

那些没有改变的错误。


原帖

我在由几个 Web API 应用程序共享的 Common 程序集中有一个非常简单的属性。就这么简单,我只是想不出是什么导致了这个异常。

I have tried to collect Fusion logs on this, but it's not logging them.

这是属性:

using System;

namespace InflowHealth.Common.ComponentModel
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
    public sealed class InflowHealthErrorContextAttribute : Attribute
    {
        // This is a positional argument
        public InflowHealthErrorContextAttribute(string errorContext)
        {
            ErrorContext = errorContext;
        }

        public string ErrorContext { get; }
    }
}

这将在路由上使用,以便稍后为过滤器内部完成的自动错误记录提供一些额外的上下文:

[Authorize(Roles = Roles.ALL_ADMINS)]
[Route("api/ControlPanelApi/PayerClassifications")]
[InflowHealthErrorContext("Error getting payer classifications.")]
public IHttpActionResult GetPayerClassifications(int clientId, bool showAllRows)
{
    return Ok(GetData(payerClassificationManager, clientId, showAllRows));
}

加载应用程序时,注册 Web API 路由时失败。这是它打破的线:

GlobalConfiguration.Configure(WebApiConfig.Register);

它抛出这个异常:

Could not load type 'InflowHealth.Common.InflowHealthErrorContextAttribute' from assembly 'InflowHealth.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

这是堆栈跟踪:

   at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
   at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
   at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
   at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit)
   at System.Reflection.RuntimeMethodInfo.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Attribute.GetCustomAttribute(MemberInfo element, Type attributeType, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttribute[T](MemberInfo element)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.IsValidActionMethod(MethodInfo methodInfo)
   at System.Array.FindAll[T](T[] array, Predicate`1 match)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Controllers.ApiControllerActionSelector.GetActionMapping(HttpControllerDescriptor controllerDescriptor)
   at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, HttpConfiguration configuration, IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<>c__DisplayClass4.<MapAttributeRoutes>b__1()
   at System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer)
   at System.Web.Http.Routing.AttributeRoutingMapper.<>c__DisplayClass2.<MapAttributeRoutes>b__0(HttpConfiguration config)
   at System.Web.Http.HttpConfiguration.EnsureInitialized()
   at System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback)
   at InflowHealthPortal.MvcApplication.Application_Start() in Global.asax.cs:line 22

最佳答案

我建议您删除 binobj 文件夹并重建项目。

当编译项目时有一个杂散的 dll 未被覆盖时,有时会发生此问题。通常在重命名输出文件时。

过去,当引用未反射(reflect)对代码和重新编译所做的更改时,执行上述操作对我有用。

Nuget 包有时也会发生同样的情况,这将导致必须删除包并重新安装它才能引用正确的 dll。

关于c# - 共享程序集中属性的 TypeLoadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47129074/

相关文章:

c# - 从 .NET 客户端对 Axis2/JAX-WS Web 服务使用多态调用

.net - 如何正确地将 char * 从用 C 编写的非托管 DLL 返回到 VB .net?

c# - 取消 HttpClient 请求 - 为什么 TaskCanceledException.CancellationToken.IsCancellationRequested 为假?

c# web api - 使用 HTTPS 运行 web 应用程序 - 添加证书并启用 SSL 但连接被拒绝

c# - 如何查找已安装的sql server 2014实例名称和版本?

c# - 让多个线程工作并等待所有线程完成的最佳方法是什么?

c# - 为什么 ActualHeight 与我在 WinRt XAML 中为网格的高度指定的不完全相同?

.net - MongoCursor 中的 Limit 和 BatchSize 有什么区别?

asp.net-web-api - JwtSecurityTokenHandler 4.0.0 重大变化?

c# - 如何将 MultipartMemoryStreamProvider 的文件内容作为字节数组获取?