2016-11-11 77 views
0

我試圖通過HTTP的方法來訪問下面的WebAPI控制器的方法發送對象

[System.Web.Http.Route("api/Users/Signin")] 
    [ResponseType(typeof(bool))] 
    public bool UserSingIn(User obj) 
    { 
     bool isuserexit = _usersRepo.UserSignIn(obj); 
     if (isuserexit == true) 
     { 
      return true; 
     } 

     return false; 
    } 

這是HTTP方法我試圖用送User obj對象,

private string USER_URL = "http://localhost:3623/api/Users"; 

    public bool GetUser(User obj) 
    { 
     try 
     { 
      HttpClient client = new HttpClient(); 
      client.BaseAddress = new Uri(USER_URL); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
      HttpResponseMessage response = client.PutAsJsonAsync("Users/Signin", obj).Result; 
      if (response.IsSuccessStatusCode) 
       return response.Content.ReadAsAsync<bool>().Result; 
      return false; 

     } 
     catch 
     { 
      return false; 
     } 

    } 

但是這以response : {StatusCode: 405, ReasonPhrase: 'Method Not Allowed', ..}

+0

我認爲你必須在你的URL中加入'/ Signin'。 –

+0

您正在向GET端點發出HTTP PUT請求。 –

+0

@ChrisPickford我把'[HttpPut]'然後得到''內部服務器錯誤'' – kez

回答

0

結束您的Web API默認只處理GET請求。如果你想使用它,你需要用HttpPut屬性來修飾它。

[HttpPut] 
[System.Web.Http.Route("api/Users/Signin")] 
[ResponseType(typeof(bool))] 
public bool UserSingIn(User obj) 
+0

然後我得到''內部服務器錯誤'' – kez

+0

@kez調試你的Web API。它應該拋出一個異常,你可以閱讀 –

0

您可以使用postAsync方法。

var data = JsonConvert.SerializeObject(dataToSave); 
var content = new StringContent(data, Encoding.UTF8, "application/json"); 
var resp = client.PostAsync(apiUrl, content).Result; 
+0

根據您的建議更改方法,但發生內部服務器錯誤var data = JsonConvert.SerializeObject(obj); var content = new StringContent(data,Encoding.UTF8,「application/json」); HttpClient客戶端= new HttpClient(); client.BaseAddress = new Uri(USER_URL); var response = cli ent.PostAsync(「Users/Signin」,內容).Result; if(response.IsSuccessStatusCode) return response.Content.ReadAsAsync ().Result; 返回false;' – kez

+0

什麼是內部服務器錯誤?你的API是[System.Web.Http.Route(「api/Users/Signin」)]你發佈到「Users/Signin」 – Miguel