dir.by  
  Поиск  
Компьютер, программы
.NET Core
 Создаем новое приложение ASP.NET Core MVC 
посмотрели 16878 раз
обновлено: 31 October 2025
Скачать пример: MyCoreWebApplication.zip ...
Step 1. Open Visual Studio
If you do not have Visual Studio installed you need install Visual Studio...
Open Visual Studio 2022
or
Open Visual Studio 2019
Step 2. Create a new blank ASP.NET Core app
Файл Program.cs содержит код
  C#     Файл Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace BookLibrary
{
     public class Program
     {
          public static void Main(string[] args)
          {
               CreateWebHostBuilder(args).Build().Run();
          }

          public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
               WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>();
     }
}
Step 3. Let's add the use of MVC in the Startup.cs file
  C#     Файл Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace BookLibrary
{
     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 https://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)
          {
               if (env.IsDevelopment())
               {
                    app.UseDeveloperExceptionPage();
               }

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


               //app.Run(async (context) =>
               //{
               //     await context.Response.WriteAsync("Hello World!");
               //});
          }
     }
}
1)
В метод Configure(IApplicationBuilder app, IHostingEnvironment env) добавили вызов app.UseMvc(routes => ...) для установки маршрута в приложении. Этот маршрут сопоставляет запросы с контроллерами и их методами.
2)
В метод ConfigureServices(IServiceCollection services) добавили вызов services.AddMvc() это остальная функциональность mvc.
3)
Закоментировали:
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
Step 4. Create a new folder Controllers
Создадим папку Controllers для хранения контроллеров.
Step 5. Create a new folder Views
Создадим папку Views для хранения представлений.
Step 6. Creating a HomeController
Создаем HomeController
Создался файл HomeController.cs
  C#     Файл HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace BookLibrary.Controllers
{
     public class HomeController : Controller
     {
          public IActionResult Index()
          {
               return View();
          }
     }
}
Step 7. Create an Index view (for the Home controller)
Нажимаем правой клавишей мыши на методе Index у контроллера Home
Создался файл Index.cshtml
  Файл Index.cshtml

@{
     Layout = null;
}

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>Index</title>
</head>
<body>
</body>
</html>
Добавим Hello! в файл Index.cshtml
  Файл Index.cshtml
@{
     Layout = null;
}

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>Index</title>
</head>
<body>
     Hello!
</body>
</html>
Step 8. Run the application
Нажимаем вверху на зеленый треугольник
Откроется страница в браузере и мы увидим
Скачать пример
 
← Previous topic
Creating a new application ASP.NET Core
 
Next topic →
Built-in IoC container in ASP.NET Core
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is .NET Core?
Creating a New .NET Core Console App
ASP.NET Core
What is ASP.NET Core?
Creating a new application ASP.NET Core
ASP.NET Core MVC
Creating a new application ASP.NET Core MVC
Built-in IoC container in ASP.NET Core
<BR>
Database (Entity Framework) in ASP.NET Core MVC
Entity Framework in the ASP.NET Core MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
<BR>
Telerik (Kendo UI) in ASP.NET Core MVC
Telerik (Kendo UI) in ASP.NET Core MVC (connect Kendo js files using NPM and Webpack)
<BR>
Authentication (login/register/logout) in the ASP.NET Core MVC application
Authentication is login/register/logout in the ASP.NET Core MVC application
Additional topics, questions
Install a new version (.NET 9) for Visual Studio 2022 | Error: NETSDK1 The current .NET SDK does not support targeting .NET 9.0. Either target .NET 7.0 or lower, or use a version of the .NET SDK that supports .NET 9.0.
Install the new version (.NET 6.0) for Visual Studio 2022. Note! .NET 6.0 is not installed and does not work for Visual Studio 2019
Installing a new version (.NET Core 2.2) for Visual Studio 2019
Choosing between ASP.NET Core and ASP.NET?
Porting code to .NET Core from the .NET Framework
Error "unable to connect to web server "iis express" | ASP.NET Core | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET Core application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW sites for learning
Sites to learn ASP.NET Core

  Ваши вопросы присылайте по почте: info@dir.by