如何在 C# ASP.NET WebAPI 中为操作方法分配别名?

csharpserver side programmingprogramming更新于 2025/4/17 21:37:17

控制器中的公共方法称为操作方法。让我们考虑一个例子,其中 DemoController 类派生自 ApiController,并包含多个操作方法,其名称与 HTTP 动词(如 Get、Post、Put 和 Delete)匹配。

示例

public class DemoController : ApiController{
   public IHttpActionResult Get(){
      //Some Operation
      return Ok();
   }
   public IHttpActionResult Post([FromUri]int id){
      //Some Operation
      return Ok();
   }
   public IHttpActionResult Put([FromUri]int id){
      //某些操作
      return Ok();
   }
   public IHttpActionResult Delete(int id){
      //某些操作
      return Ok();
   }
}

根据传入的请求 URL 和 HTTP 动词 (GET/POST/PUT/PATCH/DELETE),Web API 决定执行哪个 Web API 控制器和操作方法,例如,Get() 方法将处理 HTTP GET 请求,Post() 方法将处理 HTTP POST 请求,Put() 方法将处理 HTTP PUT 请求,Delete() 方法将处理上述 Web API 的 HTTP DELETE 请求。因此,此处 Get 方法的 Url 将是 http://localhost:58174/api/demo。

使用 ActionName 属性为操作方法提供别名。还需要在 WebApiConfig.cs 中更改路由模板。

示例

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [ActionName("FetchStudentsList")]
      public IHttpActionResult Get(){
         List<Student> students = new List<Student>{
            new Studen{
               Id = 1,
             Name = &"Mark";
            },
            new Student{
                 Id = 2,
             Name = &"John";
            }
           };
         return Ok(students);
      }
   }
}

现在我们可以使用 FetchStudentsList(别名)调用 Get() 方法。


相关文章