Получение ошибки сборки в Docker-контейнере, но не на локальных машинах - PullRequest
0 голосов
/ 18 февраля 2019

У нас возникла проблема с нашим решением, когда оно размещено в контейнере Windows, с которым я не сталкиваюсь в своей локальной сети.У меня есть проект WebAPI с использованием .Net Framework 4.6.2.Это ссылка на пользовательский пакет Nuget, который мы написали для net461; net462; netstandard2.0 ;.Как я сказал в своем названии, когда я запускаю это на моей локальной машине, все в порядке.Когда мы публикуем его в образ контейнера Docker: microsoft / dotnet-framework: 4.7-windowsservercore-10.0.14393.1884, мы получаем следующую ошибку, когда пытаемся достичь одной из конечных точек в пакете Nuget.Кто-нибудь может предложить решение или возможный следующий шаг устранения неполадок?Мы выдвинули некоторые предположения, основанные на поисках переполнения стека, но не нашли ничего, что работает.

   The ProjectAPI service is now running, press Control+C to exit.
2019-02-18 08:33:12,522 ERROR lobalExceptionLogger: CustomNugetPackageName Exception
System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
  at CustomNugetPackageName.Controllers.ReportsController.GetReport(Int32 reportId, Report& report, IHttpActionResult& unauthorized)
  at CustomNugetPackageName.Controllers.ReportsController.GetReport(Int32 reportId)
  at lambda_method(Closure , Object , Object[] )
  at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
  at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
  at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()

Я пытался установить перенаправления привязки в проекте WebAPI следующим образом:

<dependentAssembly>
   <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
   <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>

Когда я добавляю, что приложение молча завершается сбоем, когда я пытаюсь использовать Autofac для внедрения приложения NetStandard в проект WebAPI.Я был действительно озадачен тем, что, возможно, происходит, что приводит к его разрыву в контейнере.

Вот мой модуль Autofac и запуск, если вам это важно:

Модуль:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using API.Claims;
using API.ControllerBase;
using Autofac;
using Autofac.Integration.WebApi;
using ReportingServiceBase.Base;
using Module = Autofac.Module;

namespace ReportingAPIBase.Initializers
{
    /// <summary>
    /// 
    /// </summary>
    public class ReportingStartupModule : Module
    {
        /// <summary>
        /// 
        /// </summary>
        public int RestrictAccessValue { get; set; }

        /// <inheritdoc />
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule(new ReportingServiceModule());
            var assembly = Assembly.GetExecutingAssembly();  // this
            List<Type> controllers = (from t in assembly.GetTypes()
                              where t.IsClass  && typeof(ApiControllerBase).IsAssignableFrom(t)
                              select t).ToList();

            // Add Restrict Attribute
            foreach (Type controller in controllers)
            {
                TypeDescriptor.AddAttributes(controller, new API.Claims.RestrictAttribute(RestrictAccessValue, ClaimValues.FullAccess | ClaimValues.ReadOnly));
            }

            builder.RegisterApiControllers(assembly);

        }
    }
}

Запуск

using System.Reflection;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using API.Base;
using API.Common;
using API.Jwt;
using API.RoleManager;
using Autofac;
using Autofac.Integration.WebApi;
using AutoMapper;
using AutoMapper.Configuration;
using log4net.Config;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Model.Reporting;
using Owin;
using ReportingAPIBase.Initializers;
using Service;
using Service.Utilities;

[assembly: XmlConfigurator(ConfigFile = "l4n.config", Watch = true)]

namespace API
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Configure Web API for self-host.
            var config = new HttpConfiguration();

            // Register modules and types
            var builder = new ContainerBuilder();

            builder.RegisterModule(new ReportingDataPointsModule());

            // FAILS HERE
            builder.RegisterModule(new ReportingStartupModule()
            {
                RestrictAccessValue = Claims.ClaimTypes.Reports
            });

            builder.RegisterModule(new ServiceModule());
            builder.RegisterModule(new EfModule());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // Register service handles
            config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());

            builder.RegisterWebApiFilterProvider(config);
            MapperConfigurationExpression mapperConfig = new AutoMapperConfiguration().Configure();
            Mapper.Initialize(mapperConfig);
            Mapper.AssertConfigurationIsValid();

            // Build container
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            // The Autofac middleware must go before any Web Api middleware
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            WebApiConfig.Register(config, container);

            // Non-Autofac OWIN pipeline
            app.UseJsonWebTokens(container.Resolve<IRoleManager>());
            app.UseRoleManager(container.Resolve<IRoleManager>());
            app.UseWebApi(config);

            // Ensures configuration is ready
            config.EnsureInitialized();

    }
}

1 Ответ

0 голосов
/ 18 февраля 2019

Спасибо, что ты моя резиновая утка.Вскоре после публикации я нашел следующий ответ , который решил это для меня.Мне удалось отследить, что я использовал неправильную версию для перенаправления привязки.Изменение на следующее решило эту проблему.

<dependentAssembly>
   <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
   <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
...