【问题标题】:Using web API with parameters in JSON with FromUri or FromBody使用带有 FromUri 或 FromBody 的 JSON 参数的 Web API
【发布时间】:2019-06-09 02:26:59
【问题描述】:

我正在尝试使用 web api 创建一个示例。我希望接收到的 JSON 参数为 fromuri 或 frombody。当我创建客户端时,我想发送一个包含信息的对象或 JSON。

在我的网络 API 中有这个

[HttpPost]
public IHttpActionResult Post([FromUri]Peticion peticion)
{
     return Ok(peticion);
}

在我的客户中

Peticion obj = new Peticion();
obj.cliente = 2;
obj.factura = 22;
string DATA = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

var client = new HttpClient();
HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");

HttpResponseMessage message = 
client.PostAsync("http://localhost:57418//api/Deudor/",content).Result;

if (message.IsSuccessStatusCode)
{
   string result = message.Content.ReadAsStringAsync().Result;
}

但我需要在我的客户端收到 JSON。在 Web API 中,我需要接收两个参数(cliente、factura),而在我的客户端中,我需要以 JSON 格式接收该客户端的信息(名称、发票等)。

我使用了邮递员,并收到了带有信息的 JSON。但在我的客户端 C# 中我不能。

【问题讨论】:

    标签: c# asp.net json asp.net-web-api asp.net-web-api2


    【解决方案1】:

    无论使用 .net 核心还是框架,您都可以使用 HttpClient 向您的 API 发送 Get 和 Post 请求。

    POST 请求:

    HttpClient client = new HttpClient();
    var content = new StringContent(JsonConvert.SerializeObject(YourObject), Encoding.UTF8, "application/json");
    client.PostAsync("your url", content);
    

    然后就可以获取内容了 [FromBody] 您可以使用 Post 请求并从 url 获取参数,但在这种情况下最好使用 get。

    获取请求:

    HttpClient client = new HttpClient();
    client.GetAsync("your url/api/controller/id/{id}");
    

    在这两种情况下,您都需要为具有请求类型(GET、POST)的方法设置路由。 例如:在上面的 get 示例中:

    [Route("api/[controller]")
    public class SomeController
    {
      [HttpGet]
      [Route("id/{id}")]
      public someGetMethod(int id){
        //do something with id here...
      }
    }
    

    【讨论】:

    • HttpResponseMessage response= await client.PostAsync("localhost:57418/api/Deudor/",content); var Petiction = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
    【解决方案2】:

    在 Web API 中,如果控制器方法的参数不是“简单”类型,它会尝试从主体中获取值。因此,我认为您想删除 Post() 参数中的 [FromUri],因为您实际上是在请求正文中发送该信息。

    来源:https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    【讨论】:

    • 但是如何使用 JSON?我不需要在方法中使用字符串、omg 或其他任何东西...
    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2014-03-10
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多