【问题标题】:Missing Method .net core startup expection. With await next.Invoke()缺少 Method .net 核心启动预期。使用 await next.Invoke()
【发布时间】:2019-03-05 15:51:53
【问题描述】:

我不确定从哪里开始,但在将我的应用程序转换为 .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?}");
            });
        }
    }

【问题讨论】:

  • 这将有助于我们共享您的 Startup.cs 文件。这听起来像是缺少依赖(在 Swagger 上)。
  • 添加了我的 startup.cs
  • 谢谢。 “.AddSwaggerFeature”和“.UseSwaggerFeature”来自哪里?我以前没见过。
  • 如果你交换你的 app.UseSwaggerFeature(); 会发生什么到 app.UseMvc(); 之后?顺序在 Configure 方法中很重要。此外,您似乎两次调用 UseStaticFiles() - 这可能会产生意想不到的后果。
  • 另外,确保所有依赖项都更新到最新版本。

标签: asp.net-core .net-core asp.net-core-2.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

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2021-03-02
    • 2021-10-19
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多