5

I'm facing an issue with my dotnet core api with angular. I simply made a login form and a UserController to handle login requests with jwt but whenever i hit the "Login" button and call the UserController's Login method from my angular app with this:

this.http.post<any>(environment.baseUrl + `api/user/login`, user)

I always get the following message:

"The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request."

I'm looking for more than a solution on this one because i've been searching to fix it the whole day and i couldn't figure out how i could solve it. I looked at iis logs, eventviewer logs. I tried debugging and did a fair amount of internet research, but I can't find a proper way to actually handle this kind of error

Since the error is raised by the dotnet core framework, i don't really know how to determine if it's my controller that is broken or if i made a mistake while configuring services.

How do you usually figure this out? Thanks for your time and your help in advance ;)

Startup.cs:

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        var ConnectionString = Configuration.GetConnectionString("Default"); 
        services.AddDbContext<TheCompanyContext>(options => options.UseSqlServer(ConnectionString));

        services.AddControllers();
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = $"ClientApp/dist";
        });

        services.ConfigureCORS();

        var key = Encoding.ASCII.GetBytes(Configuration["AppSettings:AuthenticationSecret"]);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        services.AddAuthorization(options =>
        {
            options.FallbackPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
            app.UseHttpsRedirection();
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
        });

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

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

UserController.cs:

[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : Controller
{
    public UserController(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login([FromBody]User user)
    {
        // do login stuff
    }
}

3 Answers 3

1

I restarted a project from scratch and managed to solve the issue. I don't really don't know what solved the issue but here's the 3 main thing i did:

  • Rework CORS policy
  • Rework environment settings for both angular and dotnet
  • Solved a database connection issue

My guess is that my environment settings where kind of badly made and i was requesting the wrong api url and CORS blocked me. All of which was hiding my database issue.

Sorry i don't have a proper fix for this, but since i wasted so much time on this, restarting was easier ^^

Thanks anyway

Sign up to request clarification or add additional context in comments.

Comments

1

For me the problem was "AllowedHosts": "*" in appsettings.development.json!

Comments

0

You can try to setting environment variable ASPNETCORE_Environment=Development.

And you can also try to change "ouputPath" in angular.json . Normally it seems to be "dist/{ProjectName}". Change this to just "dist".

More details, you can refer to this discussion.

1 Comment

I already changed the outpath for my angular app to be served from the root folder. And adding the Development environment just shows me the exception page when i call the api from postman. I think i'll try to create a new project from scratch, to see if i can spot what i did wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.