Serving static files in ASP.NET 5 MVC 6

别说谁变了你拦得住时间么 提交于 2019-12-23 18:44:02

问题


My wwwroot static files aren't being resolved.

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

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:


回答1:


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.




回答2:


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 });


来源:https://stackoverflow.com/questions/32471638/serving-static-files-in-asp-net-5-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!