sak gen
sak gen

Reputation: 1

.net core web API,static file images not loading properly?

I have .net core web API PROJECT. I want to put some static images in this project.I have below code in start up file

var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
provider.Mappings[".png"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
   FileProvider = new PhysicalFileProvider(
   Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
   RequestPath = new PathString("/StaticFiles"),
   ContentTypeProvider = provider
});   

when I run or deployed this web project, i have checked under it has StaticFiles folder has test.png when I browse for test.tt/StaticFiles/test.png, or test.tt/wwwroot/StaticFiles/test.png or test.tt/wwwroot/StaticFiles/images/test.png

browser is not loading that image, it is displaying white page, where I check on network console of by F12,it is delivering response of type document and json. My problem is image is not displaying, i have tried more images but not helpful.I am sure there is image,folder in my path.

can you tell how if I browse test.png,direct hitting path to get static file .net core WEB API images?

Upvotes: 0

Views: 2321

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239400

By default, static files go into the wwwroot in your project root. Calling app.UseStaticFiles(), causes this directory to be served at the base path of the site, i.e. /. As such, a file like wwwroot/images/test.png would be available at /images/test.png (note: without the wwwroot part).

I'm not sure what in the world you're doing with the rest of this code here, but you're essentially adding an additional served directory at [project root]/MyStaticFiles, which will then be served at /StaticFiles. As such, first, test.png would have to actually be in MyStaticFiles, not wwwroot, and then you'd access by requesting /StaticFiles/test.png.

However, there's no need for this other directory. If you simply want to add some additional media types, you can do that via:

services.Configure<StaticFileOptions>(o =>
{
    var provider = new FileExtensionContentTypeProvider();
    provider.Mappings.Add(".myapp", "application/x-msdownload");
    // etc.
    o.ContentTypeProvider = provider;
});

And then just use:

app.UseStaticFiles();

Nothing else is required.

Upvotes: 2

Related Questions