Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Gán tên bí danh (Alias) cho Action Method trong C# ASP.NET WebAPI

Một phương thức public trong controller được gọi là Action method. Xét ví dụ DemoController kế thừa từ ApiController và bao gồm nhiều action methods có tên khớp với HTTP verbs như Get, Post, Put, Delete.

Ví dụ

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();
    }
}

Dựa trên URL request đến và HTTP verb (GET/POST/PUT/PATCH/DELETE), Web API quyết định controller và action method nào sẽ thực thi. URL cho phương thức Get sẽ là https://localhost:58174/api/demo.

Tên bí danh (alias) cho action method được cung cấp bằng attribute ActionName. Cũng cần thay đổi route template trong WebApiConfig.cs.

Gán tên bí danh (Alias) cho Action Method trong C# ASP.NET WebAPI

Ví dụ sử dụng ActionName

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;

namespace DemoWebApplication.Controllers
{
    public class DemoController : ApiController
    {
        [ActionName("FetchStudentsList")]
        public IHttpActionResult Get()
        {
            List students = new List
            {
                new Student { Id = 1, Name = "Mark" },
                new Student { Id = 2, Name = "John" }
            };
            return Ok(students);
        }
    }
}

Bây giờ có thể gọi phương thức Get() với tên bí danh FetchStudentsList.

Gán tên bí danh (Alias) cho Action Method trong C# ASP.NET WebAPI