执行请求时发生未处理的异常

Pan*_*hal 6 c# asp.net http

我想从WEB API获取一些数据,但在 API 调试控制台中收到如下错误消息:

 fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Endpoint WebAPI_1.Controllers.DataCTXController.Get (WebAPI_1) contains authorization metadata, but a middleware was not found that supports authorization.
Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Run Code Online (Sandbox Code Playgroud)

我使用Postman发送请求。我尝试在行之间移动 app.UseAuthorization() 并自己解决一些问题,但仍然一无所获,这就是为什么我需要你的帮助。这是我的 Startup.cs 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WebAPI_1.Data;
using Microsoft.EntityFrameworkCore;
using System.Data.Sql;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace WebAPI_1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(s => s.UseSqlServer(Configuration.GetConnectionString("Default1")));

            services.AddControllers();

            services.AddMvc(services => services.EnableEndpointRouting = false);

            services.AddCors();

            services.AddScoped<IAuthRepository, AuthRepository>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(Options =>
            {
                Options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
              endpoints.MapControllers();
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "defaultApi", template: "api/{controller}/{action}");
                routes.MapRoute(name: "default", template: "{controller}/{action=Index}/{id?}");
            }
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢帮助。

Kus*_*ush 6

由于例外是不言自明的,

通过在应用程序启动代码中对 Configure(..) 的调用中添加 app.UseAuthorization() 来配置应用程序启动。对 app.UseAuthorization() 的调用必须出现在 app.UseRouting() 和 app.UseEndpoints(...) 之间

你需要添加

app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)

在配置方法中。

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization(); // Add it here
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)