MVC Action控制方式
1.Controller 的OnActionExecuting中控制
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request["NoPower"].HasValue() == false) { filterContext.Result = Redirect("http://www.baidu.com"); return; } base.OnActionExecuting(filterContext); }
2.ActionFilterAttribute 控制
if (HttpContext.Current.Request.HttpMethod == "POST" && MyMvcHelper.RequestIsAjax) { filterContext.Result = new JsonMsg() { msg = @"请重新<a onclick=""jv.page(event).LoadView({url:'" + "~/Login".ResolveUrl() + @"'});"">登录</a>" }; HttpContext.Current.Response.StatusCode = 290; return; } return;
3.IActionInvoker 控制
//Controller 中定义协议标准 protected override IActionInvoker CreateActionInvoker() { return new MyActionInvoker(); }
public class WeiXinWebViewActionInvoker : System.Web.Mvc.ControllerActionInvoker { public override bool InvokeAction(System.Web.Mvc.ControllerContext controllerContext, string actionName) { if (controllerContext.Controller as WeiXinWebViewController == null) { return base.InvokeAction(controllerContext, actionName); } //描述了控制器的相关信息 var controllerDescriptor = this.GetControllerDescriptor(controllerContext); //描述了相关Action的相关信息 var actionDescriptor = this.FindAction(controllerContext, controllerDescriptor, actionName); if (controllerContext.HttpContext.Request.HttpMethod == "POST") { return base.InvokeAction(controllerContext, actionName); } var wxwv = controllerContext.Controller as WeiXinWebViewController; if (wxwv == null) { return base.InvokeAction(controllerContext, actionName); } var wxOAuthSetting = wxwv.GetOAuthCookie(); if (wxOAuthSetting.HasValue() == false || wxOAuthSetting.Item1.HasValue() == false) { var url = controllerContext.HttpContext.Request.Url.AbsoluteUri; wxwv.OAuthIntro(url).ExecuteResult(controllerContext); return true; } try { return base.InvokeAction(controllerContext, actionName); } catch (Exception e) { (controllerContext.Controller as MyOpenController).TransferToErrorUrl(e.Message).ExecuteResult(controllerContext); return true; } } }