Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C# ASP.NET WebAPI에서 작업 메서드에 별칭 이름을 할당하려면 어떻게 해야 합니까?

<시간/>

컨트롤러의 공용 메서드를 Action 메서드라고 합니다. DemoController 클래스가 ApiController에서 파생되고 Get, Post, Put 및 Delete와 같은 HTTP 동사와 이름이 일치하는 여러 작업 메서드를 포함하는 예를 살펴보겠습니다.

예시

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 verbv(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은 https://localhost:58174/api/demo가 됩니다.

작업 메서드의 별칭 이름은 ActionName을 사용하여 제공됩니다. 기인하다. 또한 WebApiConfig.cs에서 경로 템플릿을 변경해야 합니다.

C# ASP.NET WebAPI에서 작업 메서드에 별칭 이름을 할당하려면 어떻게 해야 합니까?

예시

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() 메서드를 호출할 수 있습니다. (별칭).

C# ASP.NET WebAPI에서 작업 메서드에 별칭 이름을 할당하려면 어떻게 해야 합니까?