我在使用带有MVC的Web API时遇到一些问题,不确定是什么导致了它,但它没有在调试模式下抛出任何异常或错误,请有人帮忙解决这个问题。
代码如下:
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 :(得分:1)
您需要从参数
中删除[FromBody]
属性
要强制Web API从请求正文中读取简单类型,请添加 [FromBody]属性为参数:
public HttpResponseMessage Post([FromBody] string name) { ... }
在此示例中,Web API将使用媒体类型格式化程序来读取 请求正文中的name值。这是一个示例客户端 请求。
POST http://localhost:5076/api/values HTTP/1.1 User-Agent: Fiddler Host: localhost:5076 Content-Type: application/json Content-Length: 7 "Alice"
当参数具有[FromBody]时,Web API使用Content-Type标头 选择格式化程序。在此示例中,内容类型为 “application / json”和请求体是一个原始的JSON字符串(不是 JSON对象)。
最多允许一个参数从邮件正文中读取。