The website I’m currently working on has a lot of AJAX incorporated in it, so my controller has a few actions which are only called in AJAX. At first I was using HttpContext.Request.IsAjaxRequest() within my action to control if the request was indeed an
Read The Full Tutorial.
The website I’m currently working on has a lot of AJAX incorporated in it, so my controller has a few actions which are only called in AJAX. At first I was using HttpContext.Request.IsAjaxRequest() within my action to control if the request was indeed an Ajax one, but I didn’t like the fact that I needed to call HttpContext in my control; it also made a lot of redundant code. That is why I decided to build an Action Filter that would do that for me.
Here’s the Action Filter
1. public class AjaxOnlyAttribute : ActionFilterAttribute 2. { 3. public override void OnActionExecuting(ActionExecutingContext filterContext) 4. { 5. if(!filterContext.HttpContext.Request.IsAjaxRequest()) 6. filterContext.HttpContext.Response.Redirect("/error/404"); 7. } 8. 9. public override void OnActionExecuted(ActionExecutedContext filterContext) 10. { 11. 12. } 13. }
public class AjaxOnlyAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if(!filterContext.HttpContext.Request.IsAjaxRequest()) filterContext.HttpContext.Response.Redirect("/error/404"); }
public override void OnActionExecuted(ActionExecutedContext filterContext) {
} }
And an implementation example view plaincopy to clipboardprint?
1. [AjaxOnly] 2. public ActionResult AjaxActionMethod() 3. { 4. .... 5. }
[AjaxOnly] public ActionResult AjaxActionMethod() { .... }
This might not be the best solution, but works pretty good for me so far!
source: helios
|