sashoalm
sashoalm

Reputation: 79467

Specify base URL for Angular ClientApp served from ASP.NET Core WebApi

I've created an ASP.NET Core project which serves an Angular app using services.AddSpaStaticFiles(), app.UseSpaStaticFiles(), app.UseSpa(), etc.

But it serves the application directly from http://localhost:1234, while I want to serve it from http://localhost:1234/angular/MyAngularApp1/, while I want to use http://localhost:1234/ for an API controller.

How can I achieve that?

Note: I need it to work in a production build. Some solutions appear to work, but in reality they work only when you run the site from Visual Studio, and stop working once you publish/deploy to IIS or Kestrel.

Upvotes: 5

Views: 4238

Answers (4)

harishr
harishr

Reputation: 18055

You can also use

         app.Map(new PathString("/MyPrefix"), appMember =>
         {
             appMember.UseSpa(spa =>
             {
                 spa.Options.SourcePath = "ClientApp";

                 if (env.IsDevelopment())
                 {
                     spa.UseAngularCliServer(npmScript: "start");
                 }
             });
         });

and for API

app.Map("/api", api => 
    {
        api.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            Authority = "https://localhost:5000/openid"
        });

        api.UseMvc();
    });

So you can run multiple parallel pipeline in same application. Read more about it here

Upvotes: 0

sashoalm
sashoalm

Reputation: 79467

Eventually I found a function that pretty much achieves this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UsePathBase("/MyPrefix/");

    if (env.IsDevelopment())
    .......

See https://www.billbogaiv.com/posts/net-core-hosted-on-subdirectories-in-nginx for more info.

Upvotes: 4

Xueli Chen
Xueli Chen

Reputation: 12695

If you want to specify base URL for view from Angular ClientApp folder , try to set href attribute of base by going to ClientApp > src > index.html like below :

<head>
 <meta charset="utf-8">
 <title>ClientApp</title>
 <base href="/ClientApp">

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

Upvotes: 2

Tony
Tony

Reputation: 20092

You can define a base url for your application like this

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "ClientApp/{controller}/{action=Index}/{id?}");
    });

Upvotes: 2

Related Questions