MVC Api控制器参数化参数
问题描述:
我正在做一个MVC 5应用程序,并且我正在调用另一个解决方案中的API控制器方法。我正在使用HttpClient()
。我打电话PostAsJsonAsync
与一些参数,一个类的实例。MVC Api控制器参数化参数
看起来像这样。
string apiUrl = "localhost:8080/api/";
ContactWF contactWF = new contactWF();
contactWF.contact_id=0;
contactWF.UserOrigin_id=20006
contactWF.ProcessState_id=2;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl + "Contact/Method", contactWF);
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<int>().Result;
}
}
我的API控制器方法是这样的。
[ActionName("Method")]
[HttpGet]
public int Method([FromBody] ContactWF userwf)
{
return 10;
}
它工作正常...
我的问题是,当我尝试序列化的参数类实例 我更换线
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl + "Contact/Method", contactWF);
与这一个
string jsonData = JsonConvert.SerializeObject(contactWF);
HttpResponseMessage response = client.PostAsJsonAsync("api/Contact/Method", jsonData).Result;
我已经有Error:405
...
它看起来像Json
字符串它不被识别为参数。
我的Json字符串看起来像这样。
"{\"Contact_id\":0,\"Description\":null,\"ProcessState_id\":2,\"Type_id\":0,\"Object_id\":0,\"Parent_id\":null}"
即将ContactWD类转换为json。
怎么了?
答
方法PostAsJsonAsync自己序列化参数对象,所以它再次序列化您的json 字符串。
如果您需要序列化对象本人出于某种原因,然后使用方法HttpClient.PostAsync
string jsonData = JsonConvert.SerializeObject(contactWF);
var stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("api/Filler/CountMensajeByUser", stringContent);
答
变化动词HttpPost在您的API控制器
[ActionName("Method")]
[HttpPost]
public int Method([FromBody] ContactWF userwf)
{
return 10;
}
更新
你并不需要序列化对象PostAsJsonAsync
HttpResponseMessage response = client.PostAsJsonAsync("api/Contact/Method", contactWF).Result;
看看示例代码微软 https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing
internal class NewIdeaDto
{
public NewIdeaDto(string name, string description, int sessionId)
{
Name = name;
Description = description;
SessionId = sessionId;
}
public string Name { get; set; }
public string Description { get; set; }
public int SessionId { get; set; }
}
//Arrange
var newIdea = new NewIdeaDto("Name", "", 1);
// Act
var response = await _client.PostAsJsonAsync("/api/ideas/create", newIdea);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
谢谢...所以我连续两次...但是,我不明白的是,如果我使用PostAsJsonAsync,在api控制器方法我应该得到一个字符串?因为现在,我得到了同一个类的实例...谢谢 – Diego
Web Api反序列化请求json体到方法argumet类。 如果你将它声明为'public int Method([FromBody] string userwf)',那么你的第二个变体具有两次序列化的对象将会工作,你将得到userwf序列化的对象。 –