【问题标题】:dotnet core 5 Webapi Send Json response to HTTPPOSTdotnet core 5 Webapi 向 HTTPPOST 发送 Json 响应
【发布时间】:2022-01-09 02:51:59
【问题描述】:
[HttpPost]
    public HttpResponseMessage Post([FromBody] clsTicketInfo ticketInfo)
    {
        try
        {
            var message = new HttpResponseMessage(HttpStatusCode.OK);
            var data = new Dictionary<string, string>
            {
              {"id","72832"},
              {"name","John"}
             };
            var jsonData = JsonConvert.SerializeObject(data);
            message.Content = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
             //      Request.CreateResponse()         
            return message;
           
        
        }
        catch (Exception ex)
        {
         return   new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
            //HttpResponseMessage(HttpStatusCode.Created, ticketInfo);
    }

在这段代码中,我想在我的 HTTP POST 中发送 Status ok 和 JSON 数据,但它不起作用。我正在使用 dotnet core 版本 5。

【问题讨论】:

    标签: .net-core asp.net-web-api


    【解决方案1】:

    你只需要这个

    public ActionResult Post([FromBody] clsTicketInfo ticketInfo)
    {
      return Ok( new  { id =72832, name = "John" } );
    }
    

    带有消息的http响应将由net mvc自动创建

    【讨论】:

      【解决方案2】:

      [HttpPost]
          public IActionResult HttpResponseMessage Post([FromBody] clsTicketInfo ticketInfo)
          {
              try
              {
                      
                    var data = new Dictionary<string, string>
                              {
                                 {"id","72832"},
                                 {"name","John"}
                    
                               };
                 var jsonData = JsonConvert.SerializeObject(data);
                  return ok(jsonData);
                 
              
              }
              catch (Exception ex)
              {
               return  Badrequest('error':ex.message)
              }
                  
          }

      IActionResult 可以在使用 ok,badrequest, notfound 时向前端发送响应。

      【讨论】:

      • 您或许应该解释一下为什么这行得通,这就是答案。
      猜你喜欢
      • 2019-01-30
      • 2013-11-24
      • 2013-09-10
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 2012-06-27
      相关资源
      最近更新 更多