简体   繁体   中英

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

I have been trying to get my head around trying to solve this problem and I have looked online to find relevant information on this. I was unable to resolve this.

My application does use a web API that was already existing as a template for this project. I think this might be causing the problem. I do not have much experience with this and I am running out of ideas to resolve this.

An additional question would be how to use other controllers without having the web API configurations active.

The web page shows the error with the url: https://localhost:(number removed)/api

If anyone needs any other code to be seen, please do ask and I will edit the post as I am not too sure where all is needed to look.

My Start up file:

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

        
    }


}

Program file

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

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

ApiUserController

// ** 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),
        };
    }     

}

Add the IPatientHutService and the implementation in the ConfigureServices method.

To view detailed error messages, uncomment the line.

//app.UseDeveloperExceptionPage();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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