Bogdan Andrei
Bogdan Andrei

Reputation: 27

How to deploy ASP.NET Core 6 Web API with vue.js frontend in IIS or Azure WebApp

I want to deploy in IIS an ASP.NET Core 6 Web API with a vue.js frontend app.

I want to deploy it as a single application, because after this test I want to deploy it in Azure as a web app.

The problem is that I get a http 404 not found error when accessing for example: http://localhost:5000/Apps/. I suspect that the app can't find index.html or doesn't know about it.

Any tips how can I configure it?

I ran npm run build and copy files from /dist folder to /Apps/ where is located the API publish.

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        builder.Services.AddDbContext<ApplicationDbContext>(c => c.UseSqlServer(builder.Configuration["DBConnection:ConnectionString"], builder =>
        {
            builder.EnableRetryOnFailure(3, TimeSpan.FromSeconds(10), null);
            builder.CommandTimeout(10800);
        }), ServiceLifetime.Transient);

        builder.Services.AddIdentity<ApplicationUser, Role>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        builder.Services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(options =>
            {
                //options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "https://accounts.google.com",
                    ValidateAudience = true,
                    ValidAudience = "http://localhost:8080/",
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"])),
                    ClockSkew = TimeSpan.FromSeconds(5) //invalidate expied token.
                };
                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        if (context.Error == "invalid_token")
                            return Task.FromException(new HttpResponseException(HttpStatusCode.Unauthorized));
                        //custom logic goes here.  At the end of your logic make sure that you
                        //"Handle" the response by calling HandleResponse, and return a 0.
                        context.HandleResponse();
                        return Task.FromResult(0);
                    }
                };
            });

        builder.Services.AddScoped<IUserService, UserService>();
        builder.Services.AddScoped<IUserRepository, UserRepository>();

        builder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowGoogleOAuth", policyBuilder =>
            {
                policyBuilder.WithOrigins("https://accounts.google.com", builder.Configuration["Client:URL"]);
                policyBuilder.WithHeaders("Content-Type", "Authorization", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Credentials", "Access-Control-Allow-Origin");
                policyBuilder.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH");
                policyBuilder.AllowCredentials(); // Allow credentials
            });
        });

        var app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseCors("AllowGoogleOAuth");
        app.UseAuthentication(); // Add this line before UseAuthorization
        app.UseAuthorization();
        app.MapControllers();
        app.Run();
    }
}

This are some settings from vue

const router = createRouter({
  history: createWebHistory(process.env.VUE_APP_BASE_URL),
  routes
})
....
VUE_APP_BASE_URL = "/Apps/"

Upvotes: 0

Views: 388

Answers (0)

Related Questions