0

我是一個非常新的asp.net web api世界。我對get(),put(),post()和delete有基本的瞭解。在asp.net web api中添加額外的get方法

在我的應用程序中,我需要兩個get()方法。以下給出解釋 -

public class StudentController : ApiController 
{ 
    public IEnumerable Get() 
    { 
     //returns all students. 
    } 

    //I would like to add this method======================= 
    [HttpGet] 
    public IEnumerable GetClassSpecificStudents(string classId) 
    { 
     //want to return all students from an specific class. 
    } 

    //I also would like to add this method======================= 
    [HttpGet] 
    public IEnumerable GetSectionSpecificStudents(string sectionId) 
    { 
     //want to return all students from an specific section. 
    } 

    public Student Get(string id) 
    { 
     //returns specific student. 
    } 
} 

angularjs控制器中已經有一個$http.get(..)

我的問題是,我怎樣才能從角度控制器調用兩個額外的get()方法。

+0

將所有的url都一樣嗎?你可能想要更新URL來包含像/學生/ filter/filterId這樣的過濾器,例如students/section/sectionId – cbass 2014-10-20 06:29:28

+0

@cbass - 我沒有任何想法。 – 2014-10-20 06:31:27

回答

2

天長地久嘛,我沒有使用asp.net的MVC。但是,你可以這樣做:

public class StudentController : ApiController 
{ 
    [Route("students")] 
    public IEnumerable Get() 
    { 
    //returns all students. 
    } 

    //I would like to add this method======================= 
    [HttpGet] 
    [Route("students/class/{classId}")] 
    public IEnumerable GetClassSpecificStudents(string classId) 
    { 
     //want to return all students from an specific class. 
    } 

    //I also would like to add this method======================= 
    [HttpGet] 
    [Route("students/section/{sectionId}")] 
    public IEnumerable GetSectionSpecificStudents(string sectionId) 
    { 
     //want to return all students from an specific section. 
    } 
    [Route("students/{id}")] 
    public Student Get(string id) 
    { 
     //returns specific student. 
    } 
} 

你也可以在這樣的routeconfig指定路線:

routes.MapRoute(
    name: "students", 
    url: "students/class/{classId}", 
    defaults: new { controller = "Student", action = "GetClassSpecificStudents", id = UrlParameter.Optional } 
); 

你一定要試試爲你的自我。你可以閱讀更多關於它herehere

不是說你有你指定的路線,你可以爲每條路線添加角度$ http.gets。

var url = "whateverdoma.in/students/" 
$http.get(url) 
    .success() 
    .error() 

var url = "whateverdoma.in/students/class/" + classId; 
$http.get(url) 
    .success() 
    .error() 

var url = "whateverdoma.in/students/filter/" + filterId; 
$http.get(url) 
    .success() 
    .error() 
+0

你解釋得很好。這種情況對我來說很清楚。非常感謝。 +1。 – 2014-10-20 07:01:35

0

你想要做的是編寫costum角度資源方法來調用你的API。

  1. 使用角度$資源,而不是$ HTTP - >這是比較常見的用法(和更多的休息導向:$資源包$ HTTP用於RESTful網絡API的情況)。

  2. Read about it

  3. 找到如何將資源添加到$資源服務。

    下面是一個例子:

    .factory('Store', function ($resource, hostUrl) { 
    var url = hostUrl + '/api/v3/store/'; 
    
    return $resource("", { storeId: '@storeId' }, {    
        getSpecific: { 
         method: 'GET', 
         url: hostUrl + '/api/v3/store-specific/:storeId' 
        } 
    }); 
    

    })

相關問題