缺少.net核心启动期望。等待下一个Invoke()

时间:2019-03-05 15:51:53

标签: asp.net-core .net-core asp.net-core-2.0

我不确定从哪里开始,但是将我的应用程序转换为.net core 2.1时出现此错误

MissingMethodException: Method not found: 'System.String Microsoft.Net.Http.Headers.StringWithQualityHeaderValue.get_Value()'.
Microsoft.AspNetCore.ResponseCompression.ResponseCompressionProvider.GetCompressionProvider(HttpContext context)

这是我的完整堆栈跟踪

System.MissingMethodException: Method not found: 'System.String Microsoft.Net.Http.Headers.StringWithQualityHeaderValue.get_Value()'.
   at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionProvider.GetCompressionProvider(HttpContext context)
   at Microsoft.AspNetCore.ResponseCompression.BodyWrapperStream.OnWrite()
   at Microsoft.AspNetCore.ResponseCompression.BodyWrapperStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.Extensions.StreamCopyOperation.CopyToAsync(Stream source, Stream destination, Nullable`1 count, Int32 bufferSize, CancellationToken cancel)
   at Microsoft.AspNetCore.Mvc.Infrastructure.FileResultExecutorBase.WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, Int64 rangeLength)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.Invoke(HttpContext context)
   at.Startup.<>c.<<Configure>b__12_0>d.MoveNext() in C:Startup.cs:line 136
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    public class Startup
    {
        private AuthorizationSettings _authorizationSettings = new AuthorizationSettings();

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonCryptoFile("connectionsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            Configuration.GetSection("AuthorizationSettings").Bind(_authorizationSettings);
            env.ConfigureNLog($"nlog.config");
        }

        public IConfigurationRoot Configuration { get; }
        public IHostingEnvironment HostingEnvironment { get; }

        public  Microsoft.AspNetCore.Http.Features.IFeatureCollection Features { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //JWT:
            services.AddTokenSecurity();
            //services.AddResponseCaching();
            // SERVICES
            services.Configure<ServiceSettings>(Configuration.GetSection("ServiceSettings"));
            var userName = Configuration.GetSection("ServiceAuthSetting:Username").Value;
            var password = Configuration.GetSection("ServiceAuthSetting:Password").Value;
            var useAuth = Configuration.GetSection("ServiceAuthSetting:Enable").Value;


            // Oracle (one connection per request via DI):
            services.Configure<DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
            services.AddTransient<DataContext>(
                r => new DataContext(r.GetRequiredService<IOptions<DatabaseSettings>>(),
                    r.GetService<ILoggerFactory>(), r.GetRequiredService<IHttpContextAccessor>()));

            // We need access to HttpContext to profile, which is off by default.
            // See: https://github.com/aspnet/Hosting/issues/793
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // Secure-by-default:
            services.Configure<AuthorizationOptions>(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes("Bearer")
                    .RequireAuthenticatedUser().Build());
            });


            //Add compression for static files and API response
            var gzipSettings = new GzipCompressionSettings();
            Configuration.GetSection("GzipCompressionSettings").Bind(gzipSettings);
            services.AddGzipCompression(gzipSettings);

            // Swagger:
            var settings = new SwaggerSettings();
            Configuration.GetSection("SwaggerSettings").Bind(settings);
            services.AddSwaggerFeature(HostingEnvironment, settings);
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //put as first middleware to make sure we capture all different files
            app.UseGzipCompression();

            loggerFactory.AddNLog();
            var serviceSettings = new ServiceSettings();
            Configuration.GetSection("ServiceSettings").Bind(serviceSettings);

            //add NLog.Web
            app.AddNLogWeb();
            app.UseLoggingMiddleware(LoggingType.All);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

           // app.UseCorsMiddleware(serviceSettings);
            //app.UseResponseCaching();

            app.Use(async (context, next) =>
            {
                var headers = context.Response.GetTypedHeaders();
                headers.CacheControl = new CacheControlHeaderValue()
                {
                    MaxAge = TimeSpan.FromSeconds(60),
                    NoStore = true,
                    NoCache = true,
                    MustRevalidate = true,
                };
                headers.Expires = DateTimeOffset.UtcNow;
                context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };

                // Do work that doesn't write to the Response.
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    var headers = context.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromSeconds(60),
                        NoStore = false,
                        NoCache = true,
                        MustRevalidate = true,
                    };
                    headers.Expires = DateTimeOffset.UtcNow;

                }
            });

            app.UseStaticFiles();

            var secret = Convert.ToBase64String(Encoding.UTF8.GetBytes(_authorizationSettings.Secret));
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidAudience = _authorizationSettings.Audience,
                    ValidIssuer = _authorizationSettings.Issuer,
                    IssuerSigningKey = new SymmetricSecurityKey(WebEncoders.Base64UrlDecode(secret)),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true
                }
            });

            app.UseSwaggerFeature();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

1 个答案:

答案 0 :(得分:1)

这是什么问题

            services.AddSwaggerGen(options =>
        {

            options.AddSecurityRequirement(security);
            options.IncludeXmlComments(GetXmlCommentsPath());
            options.DescribeAllEnumsAsStrings();
        options.EnableAnnotations();
        });

options.EnableAnnotations();是此错误的一部分,无法修复

https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation/issues/20