Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีกำหนด Alias Name ให้ Action Method ใน C# ASP.NET WebAPI

Public Method ใน Controller เรียกว่า Action Method Web API จะเลือก Action Method ตาม HTTP Verb และ URL เช่น Get() สำหรับ GET Request URL: https://localhost:58174/api/demo

ใช้ Attribute ActionName เพื่อตั้ง Alias Name และต้องปรับ Route Template ใน WebApiConfig.cs

ตัวอย่างการใช้ 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);
        }
    }
}

ตอนนี้เรียกได้ด้วย Alias Name FetchStudentsList:

วิธีกำหนด Alias Name ให้ Action Method ใน C# ASP.NET WebAPI

Route Config ต้องรองรับ Action Name:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);