2015-08-24 105 views
5

我剛與MVC 6開始具有先前創建的用於API調用和標準控制器調用單獨的控制器。在MVC 6中,不再有APIController類,這些操作可以包含在Controller類中。結合API控制器呼叫和呼叫控制器在相同的MVC 6控制器

所以在這裏我有一個TeamsController。我有一個行動回報的觀點:

[Route("Teams")] 
public ActionResult Teams() 

And then I have actions to return data : 

//GET : api/Teams 
[Route("api/Teams")] 
[HttpGet("GetAllTeams")] 
public IEnumerable<Team> GetAllTeams() 

//GET : api/Teams/5 
[Route("api/Teams/{teamId:int}")] 
[HttpGet("{teamId:int}", Name = "GetTeamById")] 
public IActionResult GetTeamById(int teamId) 

//GET : api/Teams/Chicago Bears 
[Route("api/Teams/{teamName}")] 
[HttpGet("{teamName}", Name = "GetTeamByName")] 
public IActionResult GetTeamByName(string teamName) 

//POST : api/Teams 
[Route("api/Teams/{team}")] 
[HttpPost("{team}", Name = "AddTeam")] 
public void AddTeam([FromBody]Team item) 

//PUT: api/Teams 
[Route("api/Teams/{team}")] 
[HttpPut("{team}", Name = "EditTeam")] 
public void EditTeam([FromBody]Team item) 

//DELETE : api/Teams/4 
[Route("api/Teams/{teamId:int}")] 
[HttpDelete("{teamId:int}", Name="DeleteTeam")] 
public IActionResult DeleteTeam(int id) 

我不知道如果我有這些正確配置,例如當我做在Javascript後的GET被調用,而不是POST,當我打電話而不是GetByTeamId被調用。

可有人請就如何這些路線應最好設置的建議?

編輯:這裏是JavaScript後:

var tAdd = new team(self.Id(), self.TeamName(), self.Logo()); 

        var dataObjectAdd = ko.toJSON(tAdd); 

        $.ajax({ 
         url: 'http://lovelyjubblymvc6.azurewebsites.net/api/Teams', 
         type: 'post', 
         data: dataObjectAdd, 
         contentType: 'application/json', 
         success: function (data) { 
          self.teams.push(new team(data.TeamId, data.TeamName, data.Logo)); 
          self.TeamName(''); 
          self.Logo(''); 
         }, 
         error: function (err) { 
          console.log(err); 
         } 
        }); 
+0

,你能否告訴我們後在JavaScript? –

回答

1

你幾乎沒有。

AddTeam()方法,在您的代碼段需要一個GET請求,這樣或許可以解釋爲什麼你提到的POST沒有工作。但是你想讓這個方法響應POST請求,而不是GET請求,因爲它改變了數據。 GET請求通常使用URL查詢參數完成,並且以這種方式更改數據有點危險。該方法的簽名應該是這樣的:

[Route("api/Teams/{team}")] 
[HttpGet("{team}", Name = "AddTeam")] 
public void AddTeam([FromBody]Team item) 

如果你想打電話不要忘了EditTeam()DeleteTeam()你必須發送一個PUT或DELETE請求分別

0

你有你的控制器屬性一些錯誤。

[Route("Teams")] 
public ActionResult Teams() 

And then I have actions to return data : 

//GET : api/Teams 
[HttpGet("api/Teams")] 
public IEnumerable<Team> GetAllTeams() 

//GET : api/Teams/5 
[HttpGet("api/Teams/{teamId:int}")] 
public IActionResult GetTeamById(int teamId) 

//GET : api/Teams/Chicago Bears 
[HttpGet("api/Teams/{teamName}")] 
public IActionResult GetTeamByName(string teamName) 

//POST : api/Teams 
[HttpPost("api/Teams/{team}")] 
public void AddTeam([FromBody]Team item) 

//PUT: api/Teams 
[HttpPut("api/Teams/{team}")] 
public void EditTeam([FromBody]Team item) 

//DELETE : api/Teams/4 
[HttpDelete("api/Teams/{teamId:int}")] 
public IActionResult DeleteTeam(int id) 

不需要指定動詞和路由。動詞超載使用路線。我不確定你的POST的javascript,但是如果你正在發送一個post請求,它肯定會轉到[HttpPost]的方法。