【问题标题】:An unhandled exception has occurred while executing the request执行请求时发生未处理的异常
【发布时间】:2020-06-09 03:06:53
【问题描述】:

我想从我的 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)

我使用 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?}");
            }
            );
        }
    }
}

感谢您的帮助。

【问题讨论】:

    标签: c# asp.net http


    【解决方案1】:

    由于异常是不言自明的,

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

    你需要添加

    app.UseAuthorization();
    

    在配置方法中。

    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization(); // Add it here
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    

    【讨论】:

    • 谢谢,我错过了“app.UseAuthentication();”
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多