如何在C# ASP.NET WebAPI中为Action方法赋予别名?
控制器中的公共方法称为Action方法。让我们考虑一个例子,其中DemoController类派生自ApiController,并包含多个Action方法,其名称与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){
//Some Operation
return Ok();
}
public IHttpActionResult Delete(int id){
//Some Operation
return Ok();
}
}根据传入的请求URL和HTTP动词(GET/POST/PUT/PATCH/DELETE),WebAPI决定执行哪个WebAPI控制器和Action方法,例如,Get()方法将处理HTTP GET请求,Post()方法将处理HTTP POST请求,Put()方法将处理HTTP PUT请求,Delete()方法将处理上述WebAPI的HTTP DELETE请求。因此,Get方法的URL将是https://:58174/api/demo。
使用**ActionName**属性可以为Action方法提供别名。还需要更改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()方法。

广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP