为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
拉丁的传说 2022-07-23 17:50:00
我在下面有一个家庭控制器方法,它是从 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    }  }}
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

你可以通过阅读来做到这一点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");

}


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 155 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号