我正在使用asp.net core 1.1和VisualStudio 2017社区开发一个Web应用程序,在这个应用程序中,我使用以下方式使用web-api服务:
public static T SendPostRequest<T>(string pController, T pParam){
using (HttpClient client = new HttpClient()){
string uri = API_URL + pController;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonInString = JsonConvert.SerializeObject((T)pParam);
var content = new StringContent(jsonInString, Encoding.UTF8, "application/json");
var result = client.PostAsync(uri, content).Result;
return JsonConvert.DeserializeObject<T>(result.Content.ReadAsStringAsync().Result);
}
}
当此代码到达api控制器时,我的对象为null,但jsonInString具有my对象的值。当我使用PostMan时,使用raw和JSON(applications / json),如果你看到我的对象的属性为null,则会传递相同的错误
但是如果我使用带有表单数据的邮递员,在我的apicontroller中我会回忆我的对象的数据属性,我需要你的帮助,当我从我的asp.net核心网络中的代码发送时,我如何能够接收我的对象的值,我希望你的帮助
为了能够正确处理,到达web控制器api net.core 1.1的数据,我建议你使用我在下面指出的内容。
控制器的方法
[Route("GetAll")]
[HttpPost]
...here your security directives
**example**
[AllowAnonymous]
public JsonResult GetAll([FromBody]MupdateDto data)
{
try
{
List<MupdateDto > result = Service.GetAll(data);
return Json(response);
}
catch (Exception ex)
{
response.GenerateResponse(TransData.ResponseKo(ex.Message, -69), null, null);
throw;
}
}
可以看出,在集合中,指示了呼叫路径[Route(“GetAll”)]以及要接收的参数类型[FromBody]。示例结构
public class MupdateDto
{
/// <summary>
/// data
/// </summary>
public string data{ get; set; }
/// <summary>
/// Update
/// </summary>
public DateTime Update { get; set; }
/// <summary>
/// Lparam
/// </summary>
public long Lparam { get; set; }
}
现在,在您的服务器启动时,请通过以下注意事项从邮递员处拨打电话
- 选择方法装饰中标记的类型
- 现在是时候准备数据,而不是像上面所示那样传递它们,我建议你把它们作为RAW传递,我在下面显示
还有一件事,请记住,RAW中填充的数据是模型在服务器上等待的类型,如果你有一个long类型的属性并且该RAW属性中填充的值是字符串,它将达到它的对象空值。
我希望你能正确解释我,这对你有帮助。一声问候