【问题标题】:Get body of request in ASP.NET Web Api在 ASP.NET Web Api 中获取请求正文
【发布时间】:2017-07-18 08:53:51
【问题描述】:

我遇到了这样的问题。

我在控制器中有方法,可以在 POST 请求的正文中接收数据。

这是方法。

 // POST: api/StartWorkingDays
    [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully"});
        //return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }

如何查看收到的请求正文?

感谢您的帮助。

【问题讨论】:

  • startWorkingDay 应该是您请求的正文,并检查 Request.Content
  • 好的,我可以看看startWorkingDay?@Sujith 发送给我的是什么移动应用程序
  • 是的。当您调试代码时,您可以看到 startWorkingDay 充满了您发布到它的内容。如果您发布的数据与 StartWorkingDay 模型不同,则 startWorkingDay 将为空。在这种情况下,您可以阅读 Request.Content 并查看已发布的内容。
  • 谢谢,我会试试的。@Sujith
  • 好的,它有效。但是我还有另一个问题,如果 API 在 Azure 上并且移动应用程序正在 www.******.com 上发送请求,我如何阅读请求正文?@Sujith

标签: c# asp.net asp.net-mvc-4 asp.net-web-api2


【解决方案1】:
    [HttpPost]
    public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay) 
    {
      //here above startWorkingDay is body your mobile developer will send 
       //you and data can be viewed while debugging ,
       //tell mobile developer to set content-type header should be JSON. 
       return Request.CreateResponse(HttpStatusCode.Created, "Success");
    }

为什么你的返回类型是 Json ?你应该使用 HttpResponse 。我相信您正在使用 Web api 2 。使用属性路由,如果您想以 json 格式发送响应,则从 App_Start 文件夹中的 WebApiConfig.cs 文件中删除 Xml 格式化程序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2016-03-12
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2018-10-30
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多