再说重写IHttpHandler,实现前后端分离

时间:2023-03-09 15:28:34
再说重写IHttpHandler,实现前后端分离

aspx页面第一次加载时,HttpHandler 里面是如何编译指定页面的呢?Framework提供了编译页面的API如下:

BuildManager.CreateInstanceFromVirtualPath(url, typeof(System.Web.UI.Page));根据虚拟路径生成实例。

但是url页面此时必需继承System.Web.UI.Page,就是我们常见的ASPX页面。但是这样编译时会调用aspx视图引擎来解析aspx和对应的CodeBehind类。

对于前台纯粹用JSON渲染的JS插件,解析编译ASPX页面似乎是多余的,aspx的生命周期也是复杂和没什么卵用的,那问题来了,能不能只编译类文件(当然要继承IHttpHandler),而aspx页面用html替换呢?

如下图的结构,(如何一键建立这样的文件结构下次再说,MVC中View和Controller分的太开了,不太习惯,中小型项目还是这样觉的更好。)

目标:html上发送ajax请求到.cs上,并返回数据到.html

再说重写IHttpHandler,实现前后端分离

Framework提供一个方法:

var ass = BuildManager.GetCompiledAssembly(url);根据虚拟路径得到程序集。第一次加载需要编译慢一点,之后会很快。

url可以是这样:/Portal/ListPageTmp.cs,即根据class文件路径生成Assembly,

当然此时浏览器url是/Portal/ListPageTmp.html

我们可以在前台ajax请求时就把路径由/Portal/ListPageTmp.html转换成/Portal/ListPageTmp.cs,再发送ajax,也可以在后台GetHandler方法里面转换。

我是在前台转换的如下:(把$.ajax封装一下,确保所有AJAX都调用此方法以便转换url)

$.ajax({
type: 'post',
url: ‘/Portal/ListPageTmp.cs’,
async: async,
data: data,
success: function (data) { rtn = data; },
error: function (data) { rtn["result"] = "fail"; alert("操作失败") },
dataType: 'json'
});

要想以这样ajax请求(/Portal/ListPageTmp.cs)让IIS接收到 那必然要改web.Config:不解释

<system.webServer>
<handlers>
<add name="ddd" verb="*" path="*.cs" type="App.PageBase.CSHttpHandler" />
</handlers>
</system.webServer>

以下是IHttpHandlerFactory完整代码:

  public class CSHttpHandler : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{ try
{
var ass = BuildManager.GetCompiledAssembly(url);//重要的一个方法,也见过其它的跟据url生成实例的方法,但是如果不同命名空间有同名类就不好办了。
// var d = BuildManager.CreateInstanceFromVirtualPath(url, typeof(System.Web.UI.Page)); TypeInfo pageType = ass.DefinedTypes.Where(p => p.IsClass == true && p.BaseType.BaseType == typeof(BasePage)).FirstOrDefault();
BasePage basepage = Activator.CreateInstance(pageType) as BasePage;
return (IHttpHandler)basepage;
}
catch (Exception ex)
{
throw ex;
} } public void ReleaseHandler(IHttpHandler handler)
{ } }
BasePage类,和System.Web.UI.Page类功能相当。
     public class BasePage : IHttpHandler
{ private bool _IsAjaxRequest;
private string _Action;
private ActionResult _ActionResult;
AppCache cache = new AppCache();
public BasePage()
{
this.IsCheckLogin = true; this.IsCheckAuth = true; _ActionResult = new ActionResult(); } public bool IsReusable { get; set; }
protected HttpRequest Request
{
get;
set;
}
protected HttpResponse Response
{
get;
set;
} public virtual void ProcessRequest(HttpContext context)
{
this.Request = context.Request;
this.Response = context.Response;
this.OnInit(); }
protected string Action
{
get
{
return _Action;
} }
//判断是否AJAX请求,这种模式,到这里的请求都是AJAX请求,因为HTML加载时不用触发请求到后端的。
protected bool IsAjaxRequest
{
get
{
return _IsAjaxRequest;
} }
protected virtual void OnInit()
{
_IsAjaxRequest = this.Request.Headers["X-Requested-With"] == "XMLHttpRequest" ? true : false;
_Action = Request.QueryString["Action"] == null ? "" : Request.QueryString["Action"].ToString();
form = new FormData(Request.Form);
//根据URL上的Action参数找到继承此类上的方法,并反射调用。

MethodInfo method = this.GetType().GetMethod(Action);
if (method == null)
{
throw new Exception("找不到【" + method.Name + "】方法.");
}
else
{
try
{

//绑定参数并调用,当然调用前也可以也可以做ActionFilter检查
InvokMethod(this, method);


}
catch (Exception ex)
{
 actionResut.hasError = true;
 actionResut.message = ex.InnerException.Message;
}


}

//返回json数据
ReturnData(actionResut);

         }
//绑定Action方法的参数。
protected object InvokMethod(object ins, MethodInfo method)
{ var methodParam = method.GetParameters();
object[] param = new object[methodParam.Length];
for (int i = ; i < methodParam.Length; i++)
{
string name = methodParam[i].Name;
Type paramType = methodParam[i].ParameterType;
if (paramType.IsGenericType) paramType = paramType.GetGenericArguments()[];
string ArgValue = Request.QueryString[name];
string FormValue = Request.Form[name];
string value = string.IsNullOrEmpty(ArgValue) ? FormValue : ArgValue;
if (!string.IsNullOrEmpty(value))
{
if (paramType.IsValueType)
{
param[i] = Convert.ChangeType(value, paramType);
}
else if (paramType == typeof(string))
{
param[i] = value;
}
else
{
param[i] = JsonHelper.Json2Object(value.ToString(), paramType);
}
} else
{
param[i] = null;
}
}
return method.Invoke(ins, param); }
}
ListPageTmp.html对应的类文件是这样的:
如果有ListPageTmp.html?Action=Test&Id=1&name=zhangsan的ajax请求,会根据名称找到ListPageTmp.cs,实例化后将url参数绑定到Test方法参数上执行,返回JSON.
 
     public partial class ListPageTmp :BasePage
{

[Auth(Role="Admin")]//反射调用前也可检查是否有attribute并做 拦截 ,类似MVC的ActionFilter.
public void Test(int Id,string name)
{ actionResut.Add("Name",name);
               actionResut.Add("Id",Id);
         }

     }

这样前后端就分开了。html加载完成后,根据不同需要发送ajax从服务端取json数据绑定的前台。

也实现了MVC里面的一些功能,如ActionFilter,Action参数绑定,ActionResult和MVC的不太一样。没有很复杂的ActionResult,只是封装json.

MVC是通过URL 路由 找到 Control和Action,由Action定向到View,

今天说的这个方案,是通过View找到Control和Action 执行后返回JSON给View.

唉,不知道说明白了没有。。。。