Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files in ASP.NET 5 MVC 6

My wwwroot static files aren't being resolved.

I understand that to serve static files, I need to put them in wwwroot:

wwwroot static files

favicon.ico resolves just fine, but schema/v1-0.json does not. I get the generic message:

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

I have the following wired up in Startup:

app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());
app.UseStaticFiles();

I am using DNX beta6. The above require beta5 packages. I cannot find anything online regarding serving static files in beta6. I am not sure if this could be the cause of the problem.

EDIT:

As per Sirwan's answer, I have added the following, but the json file is still not available:

var options = new StaticFileOptions
{
    ContentTypeProvider =  new JsonContentTypeProvider(),
    ServeUnknownFileTypes = true,
    DefaultContentType = "application/json"
};

app.UseStaticFiles(options);

The JsonContentTypeProvider class:

public class JsonContentTypeProvider : FileExtensionContentTypeProvider
{
    public JsonContentTypeProvider()
    {
        Mappings.Add(".json", "application/json");
    }
}

I can even see the file when browsing the server:

enter image description here

like image 762
Dave New Avatar asked Feb 10 '23 02:02

Dave New


2 Answers

Try this:

app.UseStaticFiles(new StaticFileOptions
{
    ServeUnknownFileTypes = true,
    DefaultContentType = "image/x-icon"
});

If you have multiple file types that are unknown to ASP.NET you can use FileExtensionContentTypeProvider class:

var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".json", "application/json");
provider.Mappings.Add(".ico", "image/x-icon");
// Serve static files.
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });
like image 54
Sirwan Afifi Avatar answered Feb 18 '23 01:02

Sirwan Afifi


If you're using IIS, make sure you've added the correct mime-type mappings if you don't have a catch-all managed handler. Even though you don't need web.config for your website to work, IIS will still use that for your website.

Someone correct me if I'm wrong, but I believe that if you have not configured IIS to use a managed handler to serve static files it will still default to StaticFileModule and calling app.UseStaticFiles doesn't actually do anything. If you run it using dnx, however, then app.UseStaticFiles gets used.

Just a side note, you should probably also upgrade to beta7 if you haven't already.

like image 43
Dealdiane Avatar answered Feb 18 '23 02:02

Dealdiane