2013-08-24 85 views
3

可悲的是,我無法得到最基本的事情的WebAPI的WebAPI沒有找到

$.ajax({ 
    url: "https://192.168.1.100/Api/Authentication/LogIn", 
    type: "POST", 
    contentType: "application/json", 
    data: "{ 'username': 'admin', 'password': 'MyPass' }", 
    error: function (r, s, e) { alert(e); }, 
    success: function (d, s, r) { alert(s); } 
}); 

我得到 「未找到」

API控制器定義

public class AuthenticationController : ApiController 
{ 
    [HttpPost] 
    public bool LogIn(string username, string password) 
    { 
     return true; 
    } 
} 

如果我刪除HttpPost工作並用HttpGet替換它然後做

$.ajax({ 
    url: "https://192.168.1.100/Api/Authentication/LogIn?username=admin&password=MyPass", 
    type: "GET", 
    error: function (r, s, e) { alert(e); }, 
    success: function (d, s, r) { alert(s); } 
}); 

工作正常。

WebAPI有什麼問題?

+0

試一試'data:「{username:'admin',password:'MyPass'}」' - – Yahia

回答

6

本文應該有助於回答您的一些問題。

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

我相信這裏的想法是,尤其是在一個RESTful API,你會希望將數據綁定到單一的資源,與特定的方法處理。因此,將數據推送到幾個鬆散的參數不是Web API迎合的用法。

當數據後處理,你可以告訴你的操作方法正確地結合它的參數是這樣的:

public class LoginDto { 
    public string Username { get; set; } 
    public string Password { get; set; } 
} 

[HttpPost] 
public bool LogIn(LoginDto login) { 
    // authenticate, etc 
    return true; 
} 
2

一些事情。 Yahia的改變是有效的。而且,POST需要WebAPI中的一個小方向來知道在哪裏查找他們的數據。我認爲這很愚蠢。如果您知道這是一個POST,請查看郵件正文。無論如何,將你的POST改爲這個,事情就會起作用。該屬性告訴WebAPI在主體中查看並且模型進行綁定。 enter image description here

AuthModel只是一個簡單的模型,包含您的用戶名和密碼屬性。由於WebApi想要綁定到輸入的方式,這將使您的生活更輕鬆。

這裏瞭解更多詳情: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

要善於去這些變化。

0

綁定在的WebAPI不工作,如果你使用超過1個參數。 儘管在MVC控制器中也是如此。 在WebAPI中使用一個類來綁定兩個或多個參數。閱讀有用的文章: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ 你可以解決它通過以下方式: 1.請在MVC行動(它的工作原理)相同 2.保持參數的發佈和閱讀這樣 [HttpPost] [ActionName("login")] public async Task<bool> Post() { var str= await Request.Content.ReadAsStringAsync(); // 3. Incapsulate參數上課像gyus請求提示

} 希望它幫助;)

0

POST操作只能有1個身體...... 沒有辦法送2個機構(在你的案件2串)。 因此,WebAPI解析器會期望在URL中找到它,而不是在正文中。 你可以通過設置屬性來解決它,並設置一個參數將來自URL和另一個來自身體。 一般來說,當方法中只有一個對象參數時 - 不需要屬性[FromBody]。 字符串預計將在URL中。

所以 - 你可以嘗試在URL中作爲參數發送它們(很像你在GET中做的那樣) 或者 - 構建一個類來包裝它。

我強烈建議使用POST進行登錄操作。