jQuery传送JSON給ASP.NET MVC

本文介绍了一种自定义属性“FromBodyAttribute”和“FromPartialBodyAttribute”,用于将JSON请求体中的部分或全部数据绑定到ASP.NET MVC控制器的参数上。通过使用这些属性,可以更加灵活地处理JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://blog.darkthread.net/post-2015-05-11-post-json-to-mvc-action-again.aspx

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.Validation;
using System.Web.Mvc;
 
namespace Afet.Mvc
{
    [AttributeUsage(AttributeTargets.Parameter)]
    public class FromBodyAttribute : CustomModelBinderAttribute
    {
        protected bool DictionaryMode = false;
 
        public FromBodyAttribute(bool dictionaryMode = false)
        {
            this.DictionaryMode = dictionaryMode;
        }
 
        public override IModelBinder GetBinder()
        {
            return new JsonNetBinder(DictionaryMode);
        }
 
        public class JsonNetBinder : IModelBinder
        {
 
            private bool DictionaryMode;
            public JsonNetBinder(bool dictionaryMode)
            {
                this.DictionaryMode = dictionaryMode;
            }
 
            const string VIEW_DATA_STORE_KEY = "___BodyJsonString";
 
            public object BindModel(ControllerContext controllerContext,
                ModelBindingContext bindingContext)
            {
                //Verify content-type
                if (!controllerContext.HttpContext.Request.
                    ContentType.ToLower().Contains("json"))
                    return null;
                var stringified = controllerContext.Controller
                                .ViewData[VIEW_DATA_STORE_KEY] as string;
                if (stringified == null)
                {
                    var stream = controllerContext.HttpContext.Request.InputStream;
                    using (var sr = new StreamReader(stream))
                    {
                        stream.Position = 0;
                        stringified = sr.ReadToEnd();
                        controllerContext.Controller
                            .ViewData.Add(VIEW_DATA_STORE_KEY, stringified);
                    }
                }
                if (string.IsNullOrEmpty(stringified)) return null;
 
                try
                {
                    if (DictionaryMode)
                    {
                        //Find the property form JObject converted from body
                        var dict = JsonConvert.DeserializeObject<JObject>(stringified);
                        if (dict.Property(bindingContext.ModelName) == null)
                            return null;
                        //Convert the property to ModelType
                        return dict.Property(bindingContext.ModelName).Value
                            .ToObject(bindingContext.ModelType);
                    }
                    else
                    {
                        //Convert the whole body to ModelType
                        return JsonConvert.DeserializeObject(stringified,
                            bindingContext.ModelType);
                    }
                }
                catch
                {
 
                }
                return null;
            }
        }
    }
 
    [AttributeUsage(AttributeTargets.Parameter)]
    public sealed class FromPartialBodyAttribute : FromBodyAttribute
    {
        public FromPartialBodyAttribute()
            : base(true)
        {
        }
    }
}
eg:
public ActionResult PostJson2(
            [Afet.Mvc.FromBody]ArgObject args)
        {
            return new Newtonsoft.JsonResult.JsonResult()
            {
                Data = args
            };
        }
 
        public ActionResult PostJson3(
            [Afet.Mvc.FromPartialBody]string Name,
            [Afet.Mvc.FromPartialBody]SubArgObject SubArg
            )
        {
            return new Newtonsoft.JsonResult.JsonResult()
            {
                Data = new
                {
                    ParamName = Name,
                    ParamSubArg = SubArg
                }
            };
        }
 public class ArgObject
    {
        public string Name { get; set; }
        public SubArgObject SubArg { get; set; }
    }
 
    public class SubArgObject
    {
        public string PropA { get; set; }
        [JsonProperty("PropX")]
        public string PropB { get; set; }
        [JsonIgnore]
        public string PropC { get; set; }
    }

参考资料: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值