ProgramingTip

ASP.NET Web API에서 여러 Get 메서드를 사용하여 라우팅

bestdevel 2020. 12. 3. 08:14
반응형

ASP.NET Web API에서 여러 Get 메서드를 사용하여 라우팅


저는 ASP.NET MVC와 함께 Web Api를 사용하고 익숙합니다. asp.net 웹 사이트에서 몇 가지 가지 테스트를 수행하고 있습니다.

다음 서명이있는 4 개의 get 메소드가 있습니다.

public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}

위의 모든 방법에 대해 아래 그림과 같이 웹 API를 사용하고 싶습니다.

  • 목록 Get () = api/customers/
  • 고객 GetCustomerById (문자열 Id) = api/customers/13
  • 목록 GetCustomerByCurrentMonth () = /customers/currentMonth
  • 고객 GetCustomerByUsername (문자열 사용자 이름) = /customers/customerByUsername/yasser

라우팅을 변경했지만 많이 접했습니다.

그래서, 누군가가 어떻게 구성되어 있는지 이해하고 안내하도록 도와줍니다. 감사합니다


여기 에서 Asp.net Mvc 4 및 Web Api의 라우팅

Darin Dimitrov 는 나를 위해 일하는 아주 좋은 답변을 게시했습니다.

그것은 말한다 ...

몇 가지 경로를 사용합니다.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
}

먼저 작업 이 맨 위에있는 새 경로를 추가합니다 .

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

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

그런 다음 ActionName속성을 사용 하여 다음 을 매핑합니다.

[HttpGet]
public List<Customer> Get()
{
    //gets all customer
}

[ActionName("CurrentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
    //gets some customer on some logic
}

[ActionName("customerById")]
public Customer GetCustomerById(string id)
{
    //gets a single customer using id
}

[ActionName("customerByUsername")]
public Customer GetCustomerByUsername(string username)
{
    //gets a single customer using username
}

또한 전체 경로에 대한 작업에 대한 경로를 지정합니다.

[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
   //gets all customer logic
}

[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
     //gets some customer 
}

[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
  //gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
    //gets customer by its username
}

이것에 충분한 경로 하나만

config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");

그리고 모든 작업에서 HttpGet 또는 HttpPost 속성을 지정 해야 합니다 .

[HttpGet]
public IEnumerable<object> TestGet1()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
public IEnumerable<object> TestGet2()
{
    return new string[] { "value3", "value4" };
}

이 질문에 대한 좋은 답변이 이미 많이 있습니다. 그러나 요즘에는 사용하지 않는 경로 구성이 금지되어 있습니다. 최신 버전의 MVC (.NET Core)는이를 지원하지 않습니다. 그래서 그것을 사용하는 것이 좋습니다 :)

그래서 나는 속성 스타일 라우팅을 사용하는 모든 답변에 동의합니다. 그러나 나는 모든 사람들이 경로의 기본 부분 (api / ...)을 반복했다는 것을 계속 알아 차립니다. Controller 클래스 위에 [RoutePrefix] 속성 을 적용하는 것이 좋습니다.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

많은 말을 읽은 후 마침내 알아 듣습니다.

WebApiConfig.cs에 먼저 3 개의 다른 경로를 추가했습니다.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByName",
        routeTemplate: "api/{controller}/{action}/{name}",
        defaults: null,
        constraints: new { name = @"^[a-z]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByAction",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { action = "Get" }
    );
}

그런 다음 컨트롤러 함수에서 ActionName, Route 등을 제거했습니다. 기본적으로 이것은 제 컨트롤러입니다.

// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
    Countries countries = await db.Countries.FindAsync(id);
    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
    var countries = await db.Countries
            .Where(s=>s.Country.ToString().StartsWith(name))
            .ToListAsync();

    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

이제 다음 URL 샘플 (이름 및 ID)로 언어 수 있습니다.

http : // localhost : 49787 / api / 국가 / GetCountriesByName / 프랑스

http : // localhost : 49787 / api / 국가 / 1


라우팅을 사용하지 않습니다. customersController.cs 파일에 다음 네 가지 방법을 추가하기 만하면됩니다.

public ActionResult Index()
{
}

public ActionResult currentMonth()
{
}

public ActionResult customerById(int id)
{
}


public ActionResult customerByUsername(string userName)
{
}

방법에 관련 코드를 입력합니다. 적절한 기본 라우팅을 사용하면 주어진 URL에 대한 조치 및 적절한 변수를 기반으로 컨트롤러에서 조치 결과를 가져옵니다.

기본 경로를 다음과 같이 수정하십시오.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

  // this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
  // define two types of routes 1. DefaultActionApi  and 2. DefaultApi as below

   config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
   config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });

  // decorate the controller action method with [ActionName("Default")] which need to invoked with below url
  // http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
  // http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
  // http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller


 public class DemoController : ApiController
 {
    // Mark the method with ActionName  attribute (defined in MapRoutes) 
    [ActionName("Default")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
    }

    public HttpResponseMessage GetAll()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
    }

    public HttpResponseMessage GetById()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage DemoGet()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage CustomGetDetails()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
    }
}

매개 변수가 같거나없는 두 개의 메소드가 있습니다.

[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}

[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}

AppStart=>WebApiConfig.cs메소드 등록 에서 =>에 커스텀 경로를 정의하십시오.

config.Routes.MapHttpRoute(
       name: "GetFirstList",
       routeTemplate: "api/Controllername/FirstList"          
       );
config.Routes.MapHttpRoute(
       name: "GetSecondList",
       routeTemplate: "api/Controllername/SecondList"          
       );

using Routing.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Routing.Controllers
{
    public class StudentsController : ApiController
    {
        static List<Students> Lststudents =
              new List<Students>() { new Students { id=1, name="kim" },
           new Students { id=2, name="aman" },
            new Students { id=3, name="shikha" },
            new Students { id=4, name="ria" } };

        [HttpGet]
        public IEnumerable<Students> getlist()
        {
            return Lststudents;
        }

        [HttpGet]
        public Students getcurrentstudent(int id)
        {
            return Lststudents.FirstOrDefault(e => e.id == id);
        }
        [HttpGet]
        [Route("api/Students/{id}/course")]
        public IEnumerable<string> getcurrentCourse(int id)
        {
            if (id == 1)
                return new List<string>() { "emgili", "hindi", "pun" };
            if (id == 2)
                return new List<string>() { "math" };
            if (id == 3)
                return new List<string>() { "c#", "webapi" };
            else return new List<string>() { };
        }

        [HttpGet]
        [Route("api/students/{id}/{name}")]
        public IEnumerable<Students> getlist(int id, string name)
        { return Lststudents.Where(e => e.id == id && e.name == name).ToList(); }

        [HttpGet]
        public IEnumerable<string> getlistcourse(int id, string name)
        {
            if (id == 1 && name == "kim")
                return new List<string>() { "emgili", "hindi", "pun" };
            if (id == 2 && name == "aman")
                return new List<string>() { "math" };
            else return new List<string>() { "no data" };
        }
    }
}

참고 URL : https://stackoverflow.com/questions/12775590/routing-with-multiple-get-methods-in-asp-net-web-api

반응형