How to set start page in dotnet core web api?

2019-03-17 11:55发布

问题:

I try to build a web application with dotnet core web api,but i do not know how to set index.html as start page which can be done with dotnet framework web api easily. And i tried to use app.UseDefaultFiles();app.UseStaticFiles(); to solve this problem, however, it did not work.

回答1:

If you are using a static file as the default page, the following code can help you.

 app.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new 
     List<string> { "index.html" } });

If you are using the MVC view, just add the routing role.

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


回答2:

In the launchSettings.json you can define the launchUrl

  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
    "launchBrowser": true,
    "launchUrl": "<your relative URL here>",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  }


回答3:

Using

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

is the correct way. But always use UseDefaultFiles() before UseStaticFiles Otherwise it won't work.

For reference: Core fundamentals of Static Files



回答4:

Your index.html file must be in the wwwroot folder

wwwroot / index.html

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files



回答5:

For Asp.Net Core 2.1 just right click on project -> properties -> debug and next to Launch Browser checkbox set path to the startup page you want.



回答6:

You can set any file in any folder under the wwwroot as defaut file by using options.DefaultFileNames.Add in startup.cs .

For example to use myfile.html in wwwroot/folder1/folder2/ myfile.html, you will add this in Startup.cs

options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("folder1/folder2/ myfile.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();

But some time it may not work. For example I created project File menu > New > Project , then selected .NET Core > ASP.NET Core Web Application and selected Web Api as project template. F5 always open page api/values, even though I added index.html in wwwroot folder and added following in startup.cs

DefaultFilesOptions options = new DefaultFilesOptions();
                options.DefaultFileNames.Clear();
                options.DefaultFileNames.Add("mypage.html");
                app.UseDefaultFiles(options);
               app.UseStaticFiles();

Then I opened project properties page and deleted the value in Debug/Launch browser box (which was set to api/values) Now setting of startup page is working and mypage.html is startup page. Note that this page should be in wwwroot folder as you have opted to use static files.



回答7:

If Index.html is in project root, it will be send by default.