简体   繁体   中英

Using relative Image path in Angular 2 and ASP.NET Core

I was trying to get the path of a local image file, but I can't figure out where the relative paths are located. Normally I would get them out of wwwroot/images folder, but when I try to load them from there it fails.

Where do you get relative paths in Angular 2? I used generator-aspnetcore-spa to create the application.


https://github.com/aspnet/JavaScriptServices
http://blog.stevensanderson.com/2016/05/02/angular2-react-knockout-apps-on-aspnet-core/

For example in folder ClientApp/components/app/app.ts.
Where would I put the image folder and how do I call its path ?

In the Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

the UseContentRoot defaults to the current directory from your app.

By calling app.UseStaticFiles(); in the Startup class

public class Startup
{
    ...
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...
        app.UseStaticFiles();

the static file middleware is enabled. With default settings it will serve all files in the web root folder ( <content root>/wwwroot ).

If you look at the https://github.com/aspnet/JavaScriptServices Angular2 template, you will see in the webpack.config.js that the output is stored in

output: {
    path: path.join(__dirname, 'wwwroot', 'dist'),
    filename: '[name].js',
    publicPath: '/dist/'
},

so that is <content root>/wwwroot/dist and the URL will be

 http://<whatever host and port>/dist/<my file>

The URL does not have to contain ClientApp (content root level, not accessable by static file middleware) but dist (wwwroot level).

Therefore put your images folder into ...\\wwwroot\\images and the image URL will be http://<whatever host and port>/images/<my image file> .

IN .Net Core, the app needs to know to use static files, have you got

app.UseStaticFiles();

in the Startup.cs?

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