티스토리 뷰

반응형

MVC4로 WebAPI를 사용하고 있었는데, 하나의 컨트롤러에서 여러 방식의 Get 메소드를 사용하려고 찾아보다가 해결완료

간단하게 포스트 하도록 하겠다.

 

0. 참고포스트

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

 

1. WebApiConfig

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

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

    }

 

2. Controller

 

    public class TotalController : ApiController
    {
        private DataContext db = new DataContext();

 

        [ActionName("LocaleUsers")]
        public IEnumerable<KeyValuePair<string, int>> GetLocaleUsers()

        {
            List<KeyValuePair<string, int>> results = new List<KeyValuePair<string, int>>();

            var rows = from kkk in db.MST_USER
                       group kkk by kkk.USER_LOCALE_VC into g
                       select new { Locale = g.Key, Count = g.Count() };
            foreach (var item in rows.OrderByDescending(p => p.Count))
            {
                results.Add(new KeyValuePair<string, int>(item.Locale, item.Count));
            }
            return results;
        }

        [ActionName("ShareUsers")]
        public IEnumerable<KeyValuePair<string, int>> GetShareUsers()

        {
            List<KeyValuePair<string, int>> results = new List<KeyValuePair<string, int>>();

            var rows = from kkk in db.MST_USER
                       join jjj in
                           (from iii in db.MST_SHARE_FOLDERS
                            select iii.CREATER_ID).Distinct()
                       on kkk.USER_ID equals jjj
                       group kkk by kkk.USER_LOCALE_VC into g
                       select new { Locale = g.Key, Count = g.Count() };
            foreach (var item in rows.OrderByDescending(p => p.Count))
            {
                results.Add(new KeyValuePair<string, int>(item.Locale, item.Count));
            }
            return results;
        }

 

3. 실제 사용

엑션뒤에 {id}가 없으면 DefaultApi를 사용해야하는지, ActionApi를 사용해야하는지 판단을 못하는 듯..

http://localhost:60329//api//Total//LocaleUsers//junk

http://localhost:60329//api//Total//ShareUsers//junk

 

4. Id가 숫자형이 아닌 문자형이라면

기본은 비슷한데 좀 여러군데 수정을 해야한다.

 

반응형
댓글