2016-06-09 34 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对象)。

最多允许一个参数从消息体中读取。

相关问题