第十二章:C# 与 Web 开发

第十二章:C# 与 Web 开发

编码文章call10242025-03-28 11:15:5429A+A-

12.1 ASP.NET Core 简介

ASP.NET Core 是一个跨平台的高性能框架,用于构建现代 Web 应用程序和 API。

12.2 MVC 模式

MVC(Model-View-Controller)是一种设计模式,用于将应用程序的逻辑、数据和用户界面分离。

示例代码:

csharp

复制

// Controller
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

// View (Index.cshtml)
@{
    ViewData["Title"] = "Home Page";
}

12.3 Razor 页面

Razor 页面是 ASP.NET Core 中的一种简化模型,用于构建页面驱动的 Web 应用程序。

示例代码:

csharp

复制

// PageModel
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
}

// Razor Page (Index.cshtml)
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

12.4 Web API 开发

ASP.NET Core 提供了强大的支持来构建 RESTful Web API。

示例代码:

csharp

复制

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

    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
    }

    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

课后练习题

  1. 简答题
  2. 什么是 ASP.NET Core?它的主要优势是什么?
  3. MVC 模式的主要组成部分是什么?它们的作用是什么?
  4. 什么是 Razor 页面?它与 MVC 模式有什么区别?
  5. 编程题
  6. 创建一个 ASP.NET Core MVC 应用程序,实现一个简单的用户注册页面。
  7. 编写一个 Razor 页面应用程序,显示当前日期和时间。
  8. 创建一个 ASP.NET Core Web API,实现基本的 CRUD 操作。
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4