ASP.NET AddMvc
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 AddMvc 方法。此方法对于在 ASP.NET Core 应用程序中配置 MVC 服务至关重要。
ASP.NET Core MVC 是一个使用模型-视图-控制器 (MVC) 模式构建 Web 应用程序和 API 的框架。AddMvc 注册了 MVC 所需的服务。
基本定义
AddMvc 是 ASP.NET Core 中的一个扩展方法,它将 MVC 服务添加到服务集合中。它在 Program.cs 的应用程序启动期间被调用。
此方法配置控制器、视图、Razor Pages 和标记助手等服务。它还使用默认约定设置 MVC 管道。
AddMvc 结合了 AddControllers、AddViews 和 AddRazorPages 的功能。它适用于传统的、包含视图的 MVC 应用程序。
在 .NET 8 中,AddMvc 继续支持基于控制器和基于视图的应用程序。它与先前版本保持向后兼容。
ASP.NET AddMvc 示例
以下示例演示了一个使用 AddMvc 的基本 MVC 应用程序。
var builder = WebApplication.CreateBuilder(args); // Add MVC services to the container builder.Services.AddMvc(); var app = builder.Build(); // Configure the HTTP request pipeline if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
此配置设置了一个完整的 MVC 应用程序。AddMvc 注册了包括视图和 Razor Pages 在内的 MVC 功能所需的所有服务。
using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(); } }
此控制器演示了基本的 MVC 操作。每个操作都会返回一个视图,其中一些操作通过 ViewData 传递数据。Error 操作处理异常。
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://learn.microsoft.com/aspnet/core"> building Web apps with ASP.NET Core</a>.</p> </div>
此 Razor 视图显示主页内容。@ 符号表示 Razor 代码块。ViewData 访问从控制器传递过来的数据。
该示例展示了一个完整的 MVC 设置,包括控制器、视图和路由。AddMvc 使所有这些组件能够无缝地协同工作。
来源
在本文中,我们探讨了 ASP.NET 8 中的 AddMvc 方法。此重要的配置方法可在 ASP.NET 应用程序中启用 MVC 功能。