首页>教程>.NET Core>从 ASP.NET Web API 迁移到 ASP.NET Core

此组别内的文章

需要支持?

如果通过文档没办法解决您的问题,请提交工单获取我们的支持!

从 ASP.NET Web API 迁移到 ASP.NET Core

内容纲要

ASP.NET 4.x Web API 是一种 HTTP 服务,它可到达各种客户端,包括浏览器和移动设备。 ASP.NET Core 将 ASP.NET 4.x 的 MVC 和 Web API 应用模型组合到被称为 ASP.NET Core MVC 的单一编程模型中。 本文演示从 ASP.NET 4.x Web API 迁移到 ASP.NET Core MVC 所需的步骤。

查看或下载示例代码如何下载

先决条件

查看 ASP.NET 4.x Web API 项目

本文使用在 ASP.NET Web API 2 入门中创建的 ProductsApp 项目。 在该项目中,按如下方式配置基本 ASP.NET 4.x Web API 项目。

在 Global.asax.cs 中,对 执行调用:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Http;
  6. using System.Web.Routing;
  7. namespace ProductsApp
  8. {
  9. public class WebApiApplication : System.Web.HttpApplication
  10. {
  11. protected void Application_Start()
  12. {
  13. GlobalConfiguration.Configure(WebApiConfig.Register);
  14. }
  15. }
  16. }

WebApiConfig 类位于 App_Start 文件夹中,具有一个静态 Register 方法:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web.Http;
  5. namespace ProductsApp
  6. {
  7. public static class WebApiConfig
  8. {
  9. public static void Register(HttpConfiguration config)
  10. {
  11. // Web API configuration and services
  12. // Web API routes
  13. config.MapHttpAttributeRoutes();
  14. config.Routes.MapHttpRoute(
  15. name: "DefaultApi",
  16. routeTemplate: "api/{controller}/{id}",
  17. defaults: new { id = RouteParameter.Optional }
  18. );
  19. }
  20. }
  21. }

上述类会执行以下操作:

  • 配置属性路由(虽然实际上并没有使用它)。
  • 配置路由表。 示例代码要求 URL 匹配格式 /api/{controller}/{id},其中 {id} 是可选的。

以下部分演示了如何将 Web API 项目迁移到 ASP.NET Core MVC。

创建目标项目

在 Visual Studio 中创建新的空白解决方案,并添加 ASP.NET 4.x Web API 项目进行迁移:

  1. 从“文件”菜单中选择“新建”“项目”。
  2. 选择“空白解决方案”模板,然后选择“下一步”。
  3. 将解决方案命名为 WebAPIMigration。 选择“创建”。
  4. 将现有的 ProductsApp 项目添加到解决方案。

添加要迁移到的新 API 项目:

  1. 将新的“ASP.NET Core Web 应用程序”项目添加到解决方案中。
  2. 在“配置新项目”对话框中,将项目命名为 ProductsCore,然后选择“创建”。
  3. 在“创建新的 ASP.NET Core Web 应用程序”对话框中,确认选择“.NET Core”和“ASP.NET Core 3.1” 。 选择“API”项目模板,然后选择“创建” 。
  4. 从新的 ProductsCore 项目中删除 WeatherForecast.cs 和 Controllers/WeatherForecastController.cs 示例文件。

解决方案包含两个项目。 以下部分介绍了如何将 ProductsApp 项目的内容迁移到 ProductsCore 项目。

迁移配置

ASP.NET Core 不使用 App_Start 文件夹或 Global.asax 文件。 此外,还会在发布时添加 web.config 文件。

Startup 类:

  • 替换 Global.asax。
  • 处理所有应用启动任务。

迁移模型和控制器

下面的代码演示了要为 ASP.NET Core 更新的 ProductsController

  1. using ProductsApp.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Web.Http;
  7. namespace ProductsApp.Controllers
  8. {
  9. public class ProductsController : ApiController
  10. {
  11. Product[] products = new Product[]
  12. {
  13. new Product
  14. {
  15. Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1
  16. },
  17. new Product
  18. {
  19. Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M
  20. },
  21. new Product
  22. {
  23. Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M
  24. }
  25. };
  26. public IEnumerable<Product> GetAllProducts()
  27. {
  28. return products;
  29. }
  30. public IHttpActionResult GetProduct(int id)
  31. {
  32. var product = products.FirstOrDefault((p) => p.Id == id);
  33. if (product == null)
  34. {
  35. return NotFound();
  36. }
  37. return Ok(product);
  38. }
  39. }
  40. }

更新 ASP.NET Core 的 ProductsController

  1. 将 Controllers/ProductsController.cs 和 Models 文件夹从原始项目复制到新项目。
  2. 将复制的文件的根命名空间更改为 ProductsCore
  3. 将 using ProductsApp.Models; 语句更新为 using ProductsCore.Models;

ASP.NET Core 中不存在下列组件:

  • ApiController 类
  • System.Web.Http 命名空间
  • IHttpActionResult 接口

进行以下更改:

  1. 将 ApiController 更改为 ControllerBase。 添加 using Microsoft.AspNetCore.Mvc; 来解析 ControllerBase 引用。
  2. 删除 using System.Web.Http;
  3. 将 GetProduct 操作的返回类型从 IHttpActionResult 更改为 ActionResult<Product>
  4. 将 GetProduct 操作的 return 语句简化为如下内容:C#复制return product;

配置路由

ASP.NET Core API 项目模板在生成的代码中包含终结点路由配置。

以下 UseRouting 和 UseEndpoints 调用会执行以下操作:

  • 中间件管道中注册路由匹配和终结点执行。
  • 替换 ProductsApp 项目的 App_Start/WebApiConfig.cs 文件。
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. app.UseHttpsRedirection();
  8. app.UseRouting();
  9. app.UseAuthorization();
  10. app.UseEndpoints(endpoints =>
  11. {
  12. endpoints.MapControllers();
  13. });
  14. }

按如下所示配置路由:

  1. 使用以下属性标记 ProductsController 类:C#复制[Route("api/[controller]")] [ApiController] 上述 [Route] 属性会配置控制器的属性路由模式。 [ApiController] 属性使得此控制器中所有操作都必须使用属性路由。属性路由支持标记,例如 [controller] 和 [action]。 在运行时,每个标记分别替换为应用了属性的控制器或操作的名称。 令牌执行以下操作:
    • 减少项目中的魔幻字符串的数量。
    • 应用自动重命名重构时,请确保路由与相应的控制器和操作保持同步。
  2. 启用对 ProductController 操作的 HTTP Get 请求:
    • 将 [HttpGet] 属性应用于 GetAllProducts 操作。
    • 将 [HttpGet("{id}")] 属性应用于 GetProduct 操作。

运行迁移的项目,并浏览到 /api/products。 这会显示包含三个产品的完整列表。 浏览到 /api/products/1。 此时显示第一个产品。

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
今日签到
私信列表
搜索