0

Я создал проект с ASP.NET Core MVC и AngularJS с клиентскими зависимостями NPM, Bower, Gulp. Страница index.html, созданная в папке wwwroot, не отображается как значение по умолчанию.ASP.NET Core MVC index.html не задан как страница по умолчанию

index.html

<!DOCTYPE html> 
<html ng-app="myQuotesApp"> 
<head> 
<meta charset="utf-8" /> 
<title>My Quotes App</title> 
<script src="lib/angular/angular.min.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-resource.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script> 
<script src="app.js"></script> 
</head> 
<body ng-cloak> 
<div ng-controller="quotesController"> 
    <h2>List Of Quotes</h2> 

    <ul> 
     <li ng-repeat="quote in quotes"> 
      <p>"{{quote.Content}}" - {{quote.Author}}</p> 
     </li> 
    </ul> 
</div> 

</body> 
</html> 

Startup.cs

public class Startup 
{ 
    // This method gets called by the runtime. Use this method to add services to the container. 
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 
    public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddMvc(); 
    } 
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(); 
     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 
     //app.Run(async (context) => 
     //{ 
     // await context.Response.WriteAsync("Hello World!"); 
     //}); 
     app.UseMvc(); 
    } 
} 

project.json

 { 
    "dependencies": { 
    "Microsoft.NETCore.App": { 
     "version": "1.0.1", 
     "type": "platform" 
    }, 
    "Microsoft.AspNetCore.Diagnostics": "1.0.0", 

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", 
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1", 
    "Microsoft.Extensions.Logging.Console": "1.0.0", 
    "Microsoft.AspNetCore.StaticFiles": "1.0.0", 
    "Microsoft.AspNetCore.Mvc": "1.0.1" 
    }, 

    "tools": { 
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" 
    }, 

    "frameworks": { 
    "netcoreapp1.0": { 
     "imports": [ 
     "dotnet5.6", 
     "portable-net45+win8" 
     ] 
    } 
    }, 

    "buildOptions": { 
    "emitEntryPoint": true, 
    "preserveCompilationContext": true 
    }, 

    "runtimeOptions": { 
    "configProperties": { 
     "System.GC.Server": true 
    } 
    }, 

    "publishOptions": { 
    "include": [ 
     "wwwroot", 
     "web.config" 
    ] 
    }, 

    "scripts": { 
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] 
    } 
} 

app.js файлы

(function() { 
    'use strict'; 
    angular.module('MyQuotesApp', [ 
     // Angular modules 
     'ngRoute', 
////////////////// 
     'ngResource', 
///////////////insert this ^^^^ 
     // Custom modules 
     "quotesService" 
     // 3rd Party Modules   
    ]); 
})(); 

quotesService.cs

(function() { 
'use strict'; 

var quotesService = angular.module('quotesService', ['ngResource']); 

quotesService.factory('Quotes', ['$resource', function ($resource) { 
    return $resource('/api/quotes/', {}, { 
     query: { method: 'GET', params: {}, isArray: true } 
    }); 
}]); 
})(); 

quotesController.js

(function() { 
    'use strict'; 

    angular 
     .module('myQuotesApp') 
     .controller('quotesController', quotesController); 

    quotesController.$inject = ['$scope','Quotes']; 

    function quotesController($scope, Quotes) { 

     $scope.quotes = Quotes.query(); 
     //$scope.title = 'quotesController'; 

     //activate(); 

     //function activate() { } 
    } 
})(); 

QuotesConroller.cs

namespace MyQuotesApp.api 
{ 
[Route("api/[controller]")] 
public class QuotesController : Controller 
{ 
    // GET: api/values 
    [HttpGet] 
    public IEnumerable<Quote> Get() 
    { 
     return new List<Quote> { 
      new Quote {ID=1, Content="abc", Author="abc123" }, 
      new Quote {ID=2, Content="abcd", Author="abcd123" }, 
      new Quote { ID=3, Content="abcde", Author="abcde123"} 
     }; 
     //return new string[] { "value1", "value2" }; 
    } 

    // GET api/values/5 
    [HttpGet("{id}")] 
    public string Get(int id) 
    { 
     return "value"; 
    } 

    // POST api/values 
    [HttpPost] 
    public void Post([FromBody]string value) 
    { 
    } 

    // PUT api/values/5 
    [HttpPut("{id}")] 
    public void Put(int id, [FromBody]string value) 
    { 
    } 

    // DELETE api/values/5 
    [HttpDelete("{id}")] 
    public void Delete(int id) 
    { 
    } 
} 
} 
+1

В mvc вы не задаете страницы по умолчанию, а используете маршрутизацию, чтобы решить, какая страница будет обслуживаться. – Baahubali

+0

У меня есть демо в этом использовании index.html, который помещен в папку wwwroot, и он работает как defauls, но в моем коде не работает. –

+0

введите код для маршрутизации класса – Baahubali

ответ

0

У вас нет действия с указанием того, что делать, когда вы получаете запрос GET для корень (/).

[HttpGet('/')] 
public IActionResult Index() 
{ 
    return View(); 
} 

В MVC, при указании return View(); без предоставления определенной точки зрения, он будет искать вид имени Action (имя метода контроллера, в этом случае Index)

+0

его запуск, но index.html не запускается –

+0

@PrafulChauhan Где находится ваш файл 'index.html'? Он должен по умолчанию находиться в 'Views/Home/Index.html' или' Views/Index.html', я считаю. – James

+0

index.html находится в wwwroot сложенном, в asp.net ядро ​​с угловыми также размещается в wwwroot folded .. –

0

тот же вопрос - index.html находится в папке wwwroot в соответствии с основными рекомендациями asp.net. так как, чтобы эта страница отображалась как значение по умолчанию для сайта? Я понял (с MVC5 дней), что контроллеры не обслуживают страницы «.html»?

0

Необходимо добавить app.UseDefaultFiles() и app.UseStaticFiles().

app.UsedefaultFiles() будет искать файл по умолчанию, как default.html или index.html внутри wwwrootfolder.

 Смежные вопросы

  • Нет связанных вопросов^_^