Trying to serve Index.html in ASP.NET Core project and /api/values elsewhere

╄→尐↘猪︶ㄣ 提交于 2020-06-17 00:59:33

问题


I've got a SPA app that I've loaded into my /wwwroot directory and it has an index.html file that I want loaded by default. I then want the normal controller files to work. That is the default values controller should run. Below is my startup. It does render wwwroot/index.html but then /api/values does not work (unless I comment out UseStaticFiles, then index.html does not).

How can I get both index.html to load and also the values controller to work.

startup.cs

public void Configure(
        IApplicationBuilder app)
    {
        DefaultFilesOptions options = new DefaultFilesOptions();
        options.DefaultFileNames.Clear();
        options.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(options);
        app.UseStaticFiles();
        app.UseMvc();
    }

the values controller...

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

回答1:


The following seems to solve my problem.

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        DefaultFilesOptions options = new DefaultFilesOptions();
        options.DefaultFileNames.Clear();
        options.DefaultFileNames.Add("index.html");


        app.UseDefaultFiles(options);
        app.UseStaticFiles();

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

To test it I added wwwroot/index.html and a simple /home/contact controller and view class (no /home/index controller or view).



来源:https://stackoverflow.com/questions/48144536/trying-to-serve-index-html-in-asp-net-core-project-and-api-values-elsewhere

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