How to receive Json data by MVC



public class DemoModel
{
        public string Name { get; set; }
        public int Age { get; set; }
}

[HttpPost]
public ActionResult About(DemoModel model)
{
            return Json(model);
}

[HttpPost]
public ActionResult About(string Name, int Age)
{
            return Json(model);
}

See if this code is very familiar. It's commonly used, right? Now in another scenario, a works with B. B sends a callback to A. A knows that B recalls sending the callback data, and sends the Json format data, but the format content B doesn't give the document,

At this time, the test can indeed receive the callback request sent by B, but it is not aware that the data format is in a hurry. At this time, B can not be contacted temporarily, and B's project has been online and running well without any problem. At this time, how can I know the callback interface of B

What did you send?

Does a small partner with development experience say it's not easy?

See trick

//Post Parameters are coming.
StringBuilder sb = new StringBuilder();
string[] keys = Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
                sb.Append(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
//Get Parameters are coming.
StringBuilder sb = new StringBuilder();
foreach (String key in Request.QueryString.AllKeys)
{
       sb.Append("Key: " + key + " Value: " + Request.QueryString[key]);
}

Oops, I'll go. Why are they all empty? No, according to the development experience, Post and Get are one way

But I'm not worried

In fact, many of my small development partners are using MVC because it is so easy to use a lot of things. Microsoft is ready for you, because it is so convenient, so we take some situations for granted

Let's talk about the miscellaneous implementation of Microsoft

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    DemoModel model = filterContext.ActionParameters["model"] as DemoModel;
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    filterContext.HttpContext.Request.InputStream.Position = 0;
    using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream))
    {
        string json = reader.ReadToEnd();
        //Json We got the string. We know that other partners sent it Json Data format
    }
}    

This article would like to explain the problem you understand, like to point a praise!

Keywords: ASP.NET JSON

Added by Batosi on Fri, 03 Jan 2020 19:08:42 +0200