<handlers>
<!--type为处理jsonHandler的命名空间加类名-->
<!--第二个为程序集的名称-->
<add name="JsonApi" verb="*" path="/Json/*" type="JsonFactory.JsonHandler,JsonFactory" />
</handlers>
</system.webServer>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;
namespace JsonFactory
{
public class JsonHandler : IHttpHandler, IRequiresSessionState
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetExpires(DateTime.Now);
context.Response.ContentType = jsonType;
this.SetResponse(context);
context.Response.End();
}
private const string jsonType = "application/json";
private const string javascriptType = "application/javascript";
private void SetResponse(HttpContext context)
{
string[] segments = context.Request.Url.Segments;
string action = "";
if (segments.Length < 3)
{
return;
}
action = segments[2].Trim('/').ToLower();
JsonBase json = null;
switch (action)
{
case "user":
json = new InformationJsonData(context.Request);
break;
default:
break;
}
if (json == null)
{
return;
}
string responseString = json.OutputData();
//var compress = new PageCompression(context);
//compress.GZipEncodePage();
context.Response.Write(responseString);
}
}
}
ajax请求类似路由API(MVC):
//API路由
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
System.Web.Routing.RouteTable.Routes.MapHttpRoute("DefaultAPi",
"api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
public class MyController : ApiController
{
/// <summary>
/// 获取单个出团日期日期数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[AcceptVerbs("POST", "GET")]
public string GetHelloWorld(int id)
{
return "hello world" + id;
}
$(function () {
/*
$.post("/Json/Information/admin", function (d) {
alert(d);
});*/
var id = 1;
$.post("/API/My/GetHelloWorld/" + id, function (d) {
alert(d);
});
})
}