using
System;
&nbs
p;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.T
hreading.Tasks;
namespace Happy.Web
{
p
ublic interface IWantAutoBind
PRo
PErty
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
n
amespace Happy.Web
{
[Attribute
usage(AttributeT
argets.Property, AllowMultiple = true)]
public sealed class AutoBind : Attribute
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Happy.ExtensionMethods.Reflection;
namespace Happy.Web
{
public class JsonBinderModule : IHttpModule
{
public void In
IT(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
if (!(HttpContext.
current.CurrentHandler is IWantAutoBindProperty))
{
return;
}
VAR properties = HttpContext.Current.CurrentHandler.GetType().GetProperties();
for
each (var property in properties)
{
if (!property.Is
defined(typeof(AutoBind), true))
{
continue;
}
string
JSON = HttpContext.Current.Request[property.Name];
var value = JsonConvert.DeserializeObject(json, property.PropertyType);
property.SetValue(HttpContext.Current.Handler, value);
}
}
public void Dispose()
{
}
}
}
<?
XMl version="1.0" encoding="utf-8"?>
<
configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
<httpModules>
<add name="JsonBinderModule" type="Happy.Web.JsonBinderModule"/>
</httpModules>
</system.web>
</configuration>
/// <reference path="
../ext-all-debug-w-comments.js" />
var data = {
Name: '段光伟',
Age: 28
};
Ext.Ajax.request({
url: '../handlers/JsonBinder
test.ashx',
method: 'POST',
params: { user: Ext.encode(data) }
});
<%@ WebHandler Language="C
#" Class="JsonBinderTest" %>
using System;
using System.Web;
using Happy.Web;
public class JsonBinderTest : IHttpHandler, IWantAutoBindProperty
{
[AutoBind]
public User user { get; set; }
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/pl
ain";
context.Response.Write(string.Format("姓名:{0},年龄:{1}", user.Name, user.Age));
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}