前端PostJosn,后端转化相应的类

时间:2021-10-10 12:07:56
/// <summary>
/// JsonPost特性类
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class JsonPostAttribute : ActionFilterAttribute
{
/// <summary>
/// 类型
/// </summary>
public Type ParamType { get; set; }

/// <summary>
/// .ctor
/// </summary>
public JsonPostAttribute(Type paramType)
{
ParamType
= paramType;
}

/// <summary>
/// .ctor
/// </summary>
public JsonPostAttribute()
{

}

/// <summary>
/// Action执行前过滤器
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filterContext.HttpContext.Request.InputStream,
System.Text.Encoding.GetEncoding(
"utf-8")))
{
var data = sr.ReadToEnd();
var methodInfo = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo;
if (ParamType == null)
{
foreach (var p in methodInfo.GetParameters())
{
ParamType
= p.ParameterType;
break;
}
}

if (ParamType != null)
{
var callback = data.ToInstance(ParamType);
foreach (var p in methodInfo.GetParameters())
{
if (p.ParameterType.FullName == ParamType.FullName)
{
filterContext.ActionParameters[p.Name]
= callback;
break;
}
}
}
}
}
}

 

调用 方式

 

        [JsonPost]
public JsonResult Create(CreateOrUpdateOrderReq req)
{

return req!=null && req.Id>0;
}

 

前端Post

{"Id":1}

 

另一种实现

客户端调用时 header 里 添加

 Content-Type: application/json;charset=UTF-8

则MVC会自动解析