简体   繁体   English

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

[英]How to read http post request data as JSON in MVC home controller?

I have a home controller method below which is invoked from a http post request.我有一个主控制器方法,它是从 http post 请求调用的。 I need to read the request data and send it to the view.我需要读取请求数据并将其发送到视图。 Is there a way to look at the raw data without creating parameters in the SaveResponse() ?有没有办法查看原始数据而不在 SaveResponse() 中创建参数? Thanks for any suggestions.感谢您的任何建议。

 public ActionResult SaveResponse()
    {
        //Read the http post request body as json and send it to view
        //HttpContext.Request.RequestContext

        return View("CallbackView");
    }

The request body will be in JSON format.请求正文将采用 JSON 格式。

{
   "customers":
  {
    "firstName": "Test”,
    "lastName": “Lastname”,
    "fullAddress": 
    {
        "streetAddress": "123 springs lane",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    }
  }
}

You can do it by reading Request.InputStream你可以通过阅读Request.InputStream

[HttpPost]
public ActionResult SaveResponse()
{
    string json;
    using (var reader = new StreamReader(HttpContext.Request.InputStream))
    {
        json = reader.ReadToEnd();
    }

    return View("CallbackView");
}

or you can accept string parameter and model binder will do everything for you, but you need to pass data as a string via json parameter.或者您可以接受string参数,模型绑定器将为您完成所有工作,但您需要通过json参数将数据作为字符串传递。 Some of available options一些可用选项

  • Set Content-Type: application/json and payload like {"json": "{id:44}"}设置Content-Type: application/json和有效负载,如{"json": "{id:44}"}

  • Set Content-Type: x-www-form-urlencoded and payload like json={id:44}设置Content-Type: x-www-form-urlencoded和有效负载,如json={id:44}

Action行动

[HttpPost]
public ActionResult SaveResponse(string json)
{
    return View("CallbackView");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM