In ASP.NET MVC, deserialize JSON prior to or in controller's action method

后端 未结 5 781
深忆病人
深忆病人 2020-12-25 13:27

I am working on a website that will post a JSON object (using jQuery Post method) to the server side.

{ 
    \"ID\" : 1,
    \"FullName\" : {
       \"First         


        
5条回答
  •  Happy的楠姐
    2020-12-25 14:21

    I resolved my problem by implementing an action filter; code sample is provided below. From the research, I learned that there is another solution, model binder, as takepara described above. But I don't really know that pros and cons of doing in either approach.

    Thanks to Steve Gentile's blog post for this solution.

    public class JsonFilter : ActionFilterAttribute
        {
            public string Parameter { get; set; }
            public Type JsonDataType { get; set; }
    
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
                {
                    string inputContent;
                    using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
                    {
                        inputContent = sr.ReadToEnd();
                    }
    
                    var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
                    filterContext.ActionParameters[Parameter] = result;
                }
            }
        }
    
    [AcceptVerbs(HttpVerbs.Post)]
    [JsonFilter(Parameter="user", JsonDataType=typeof(User))]
    public ActionResult Submit(User user)
    {
        // user object is deserialized properly prior to execution of Submit() function
    
        return View();
    }
    

提交回复
热议问题