gpt4 book ai didi

c# - HttpClient.PostAsJsonAsync 在 Debug模式下不工作或出现任何错误

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:42 25 4
gpt4 key购买 nike

我在将 Web API 与 MVC 结合使用时遇到了一些问题,不确定是什么原因造成的,但它在 Debug模式下不会抛出任何异常或错误,请有人帮助解决这个问题。

代码如下:

MVC Controller 调用:

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;
}

}

网络 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);

}

最佳答案

您需要从参数中删除[FromBody] 属性

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

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

In this example, Web API will use a media-type formatter to read the value of name from the request body. Here is an example client request.

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

"Alice"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body.

关于c# - HttpClient.PostAsJsonAsync 在 Debug模式下不工作或出现任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37736599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com