2016-06-09 130 views
2

我在使用MVC的Web API時遇到一些問題,不確定是什麼導致了它,但它不會在調試模式下拋出任何異常或錯誤,請有人可以幫助解決這個問題。HttpClient.PostAsJsonAsync不能正常工作或在調試模式下給出任何錯誤

代碼如下:

MVC控制器調用:

PortalLogonCheckParams credParams = new PortalLogonCheckParams() {SecurityLogonLogonId = model.UserName, SecurityLogonPassword = model.Password}; 

SecurityLogon secureLogon = new SecurityLogon(); 

var result = secureLogon.checkCredentials(credParams); 

數據訪問對象方法:

public async Task <IEnumerable<PortalLogon>> checkCredentials(PortalLogonCheckParams credParams) 
{ 
    using (var client = new HttpClient()) 
    { 
     client.BaseAddress = new Uri("http://localhost:50793/"); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

     // Check Credentials 

     //Following call fails 

     HttpResponseMessage response = await client.PostAsJsonAsync("api/chkPortalLogin", credParams); 


     if (response.IsSuccessStatusCode) 
     { 
      IEnumerable<PortalLogon> logonList = await response.Content.ReadAsAsync<IEnumerable<PortalLogon>>(); 
      return logonList; 
     } 
     else return null; 
    } 

} 

的Web API:

[HttpPost] 
public IHttpActionResult chkPortalLogin([FromBody] PortalLogonCheckParams LogonParams) 
{ 

    List<Mod_chkPortalSecurityLogon> securityLogon = null; 

    String strDBName = ""; 

    //Set the database identifier   
    strDBName = "Mod"; 

    //Retrieve the Logon object 
    using (DataConnection connection = new DataConnection(strDBName)) 
    { 
     //Retrieve the list object 
     securityLogon = new Persistant_Mod_chkPortalSecurityLogon().findBy_Search(connection.Connection, LogonParams.SecurityLogonLogonId, LogonParams.SecurityLogonPassword); 
    } 

    AutoMapper.Mapper.CreateMap<Mod_chkPortalSecurityLogon, PortalLogon>(); 

    IEnumerable<PortalLogon> securityLogonNew = AutoMapper.Mapper.Map<IEnumerable<Mod_chkPortalSecurityLogon>, IEnumerable<PortalLogon>>(securityLogon); 


    return Ok(securityLogonNew); 

} 
+0

您是否嘗試過通過fiddler或SOAP UI進行調用,如果您如此,響應代碼是什麼? – din

+3

「不工作」是什麼意思?哪裏出問題了?你期望發生什麼? – DavidG

+0

從參數中刪除'[FromBody]'屬性。 – Nkosi

回答

1

您需要從參數

Using [FromBody]

要強制的Web API來讀取請求主體一個簡單類型刪除[FromBody]屬性,添加 [FromBody]屬性參數:

public HttpResponseMessage Post([FromBody] string name) { ... } 

在這個例子中,Web API將會使用媒體格式化程序從請求主體讀取名稱的 值。這裏是一個示例客戶端 請求。

POST http://localhost:5076/api/values HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:5076 
Content-Type: application/json 
Content-Length: 7 

"Alice" 

當一個參數具有[FromBody],網絡API使用Content-Type頭 選擇一個格式化器。在此示例中,內容類型爲 「application/json」,請求正文爲原始JSON字符串(不是 JSON對象)。

最多允許一個參數從消息體中讀取。

相關問題