如何在 MVC 主控制器中将 http post 请求数据读取为 JSON?

我在下面有一个家庭控制器方法,它是从 http post 请求调用的。我需要读取请求数据并将其发送到视图。有没有办法查看原始数据而不在 SaveResponse() 中创建参数?感谢您的任何建议。


 public ActionResult SaveResponse()

    {

        //Read the http post request body as json and send it to view

        //HttpContext.Request.RequestContext


        return View("CallbackView");

    }

请求正文将采用 JSON 格式。


{

   "customers":

  {

    "firstName": "Test”,

    "lastName": “Lastname”,

    "fullAddress": 

    {

        "streetAddress": "123 springs lane",

        "city": "New York",

        "state": "NY",

        "postalCode": 10021

    }

  }

}


拉丁的传说
浏览 156回答 1
1回答

UYOU

你可以通过阅读来做到这一点Request.InputStream[HttpPost]public ActionResult SaveResponse(){    string json;    using (var reader = new StreamReader(HttpContext.Request.InputStream))    {        json = reader.ReadToEnd();    }    return View("CallbackView");}或者您可以接受string参数,模型绑定器将为您完成所有工作,但您需要通过json参数将数据作为字符串传递。一些可用的选项设置Content-Type: application/json和有效载荷{"json": "{id:44}"}设置Content-Type: x-www-form-urlencoded和有效载荷json={id:44}行动[HttpPost]public ActionResult SaveResponse(string json){    return View("CallbackView");}
打开App,查看更多内容
随时随地看视频慕课网APP