【问题标题】:Asp.Net Core 1.1 consume web apiAsp.Net Core 1.1 消费web api
【发布时间】:2017-10-11 11:56:03
【问题描述】:

我正在使用带有 VisualStudio 2017 社区的 asp.net core 1.1 开发一个 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 控制器时,我的对象为空,但 jsonInString 具有我的对象的值。 当我使用 PostMan,使用 raw 和 JSON(applications/json),如果你看到我的对象的属性是空值,同样的错误通过了

但是,如果我使用带有表单数据的邮递员,在我的 apicontroller 中我接收对象的数据属性,我需要你的帮助,当我从我的 asp.net 核心网络中的代码发送时,我如何接收我的对象的值,希望对你有所帮助

【问题讨论】:

  • 更改FromForm -> FromBody
  • 是的!只需将 FromForm 更改为 FromBody

标签: c# asp.net-web-api asp.net-mvc-5 asp.net-core asp.net-web-api2


【解决方案1】:

为了能够正确处理,到达 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 传递,如下所示

你能确定我发送的数据类型是 JSON 错误吗

还有一件事,请记住,RAW 中填写的数据是模型在服务器上等待的类型,如果您有一个 long 类型的属性并且该 RAW 属性中填写的值是字符串,它的对象就会达到null。

希望您对我的解释正确,这将对您有所帮助。 问候

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多