繁体   English   中英

localhost 当前无法处理此请求。 HTTP 错误 500 - 对于 asp.Net Core

[英]localhost is currently unable to handle this request. HTTP ERROR 500 - For asp.Net Core

我一直在努力解决这个问题,我在网上寻找相关信息。 我无法解决这个问题。

我的应用程序确实使用了一个已经存在的 Web API 作为该项目的模板。 我认为这可能是导致问题的原因。 我在这方面没有太多经验,而且我没有想法来解决这个问题。

另一个问题是如何在没有激活 Web API 配置的情况下使用其他控制器。

网页显示错误,网址为:https://localhost:(number removed)/api

如果有人需要查看任何其他代码,请务必询问,我将编辑该帖子,因为我不太确定需要查看的所有内容。

我的启动文件:

    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)
    {   
        
        // ** Add Cookie Authentication via extension method **
        //services.AddCookieAuthentication();

        // ** Add Cookie and Jwt Authentication via extension method **
        services.AddCookieAndJwtAuthentication(Configuration);

        // ** Enable Cors for and webapi endpoints provided **
        services.AddCors();
        
        // Add UserService to DI - change to use real UserService           
        services.AddTransient<SolutionNameService,SolutionNameServiceDb>();

        // ** Required to enable asp-authorize Taghelper **            
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        
        services.AddControllersWithViews();

        
    }

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


            // seed users - using service provider to get UserService from DI
            Seeder.Seed(provider.GetService<SolutionNameService>());
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        // ** configure cors to allow full cross origin access to any webapi end points **
        app.UseCors(c => c.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        // ** turn on authentication/authorisation **
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

        
    }


}

程序文件

    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

接口用户控制器

// ** This is a Demo WebAPI Controller provides User Login Using JWT Token **

[ApiController]    
[Route("api")]     
// set default auth scheme as we are using both cookie and jwt authentication
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class UserApiController : ControllerBase
{
    private readonly IPatientHutService _svc;       
    private readonly IConfiguration _config; // jwt settings
  
    public UserApiController(IPatientHutService service, IConfiguration _configuration)
    {      
        _config = _configuration;            
        _svc = service;
    }

    // POST api/login
    [AllowAnonymous]
    [HttpPost("login")]
    public ActionResult<User> Login(UserLoginViewModel login)        
    {                     
        var user = _svc.Authenticate(login.Email, login.Password);            
        if (user == null)
        {
            return BadRequest(new { message = "Email or Password are incorrect" });
        }
        // sign jwt token to use in secure api requests
        var authUser = SignInJwt(user);

        return Ok(authUser);
    }  

    // POST api/login
    [AllowAnonymous]
    [HttpPost("register")]
    public ActionResult<User> Register(UserRegisterViewModel reg)        
    {                     
        var user = _svc.AddUser(reg.Name, reg.Email, reg.Password, reg.Role);
        if (user == null)
        {
            return BadRequest(new { message = "User Could not be Registered" });
        }
        // sign jwt token to use in secure api requests
        var authUser = SignInJwt(user);

        return Ok(authUser);
    }  

    // Sign user in using JWT authentication
    private UserAuthenticatedViewModel SignInJwt(User user)
    {
        return new UserAuthenticatedViewModel
        {
            Id = user.Id,
            Name = user.Name,
            Email = user.Email,              
            Role = user.Role,
            Token = AuthBuilder.BuildJwtToken(user, _config),
        };
    }     

}

在 ConfigureServices 方法中添加 IPatientHutService 和实现。

要查看详细的错误消息,请取消注释该行。

//app.UseDeveloperExceptionPage();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM