using System;
using System.Web;
using Newtonsoft.Json;
using System.Reflection;
using System.Web.SessionState;
using System.Runtime.Serialization;
namespace LYFZ.WanYuKeFu
{
public struct AjaxResult
{
int _code;
public int code
{
get { return _code; }
}
string _info;
public string info
{
get { return _info; }
}
object _data;
public object data
{
get { return _data; }
}
public AjaxResult(int code, string info, object data = null)
{
this._code = code;
this._info = info;
this._data = data;
}
public AjaxResult(EnumCode.AjaxResultCode ResultCode, string info, object data = null)
{
this._code = (int)ResultCode;
this._info = info.Trim();
this._data = data;
}
public AjaxResult(EnumCode.AjaxResultCode ResultCode, object data = null)
{
this._code = (int)ResultCode;
this._info = ResultCode.ToString().Trim();
this._data = data;
}
public AjaxResult(EnumCode.AjaxResultCode ResultCode, string msg)
{
this._code = (int)ResultCode;
this._info = msg;
this._data = new { };
}
}
public class ApiBase : IHttpHandler, IRequiresSessionState
{
protected HttpContext context;
protected HttpSessionState Session;
///
/// 用户子类做初始化的中间操作
///
///
public virtual void Initialize(HttpContext context) {
}
public virtual void ProcessRequest(HttpContext context)
{
this.context = context;
this.Session = context.Session;
context.Response.ContentType = "application/json";
// 设置允许跨域请求
// context.Response.Headers.Add("Access-Control-Allow-Origin", "http://"+context.Request.Url.Host+":8080");
// context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
// context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
// context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Type thisType = this.GetType();
string[] PathInfos = context.Request.PathInfo.Split('/');
MethodInfo methodInfo = thisType.GetMethod(PathInfos[1]);
object[] parametersObj = new object[] { context };
// string callback = context.Request.QueryString["callback"];
try
{
Initialize(context);
ajaxReturn((AjaxResult)methodInfo.Invoke(this, parametersObj));
}
catch (NullReferenceException)
{
ajaxReturn(new AjaxResult(404, "Operation Not Found"));
}
catch (Exception e)
{
ajaxReturn(new AjaxResult(404, e.Message));
}
}
public void ajaxReturn(AjaxResult result, string callback = null)
{
string responseBody = JsonConvert.SerializeObject(result);
//if (!String.IsNullOrEmpty(callback))
//{
// responseBody = callback + " ( " + responseBody + " ) ";
//}
context.Response.Write(responseBody);
}
///
/// 读取某个Session对象值
///
/// Session对象名称
/// Session对象值
public object GetObjectFormSession(string strSessionName)
{
return this.Session[strSessionName];
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class EnumCode
{
public enum AjaxResultCode
{
参数错误 = -777,
内容超长 = -7,
授权失败 = -1,
请求失败 = -999,
推送失败 = -900,
请求成功 = 200,
没有找到目标用户注册的APP设备 = -1000,
}
}
}