In today’s web applications, there is an overwhelming reliance on Javascript. It's used all the time, for handling all sorts of behavior,i.e. building your entire framework, loading and manipulating DOM elements, etc.
Often, it can be useful to determine how specific requests come into your application, and, where they are originating from, because you might want to limit what your user can and cannot access via plain GET and POST requests.
IsAjaxRequest() = false;
Previously, ASP.NET MVC applications could easily check if a request was being made via AJAX, through the aptly named IsAjaxRequest() method which was an available method on the Request object, as shown below:
- public ActionResult YourActionName()
- {
- // Check if the request is an AJAX call
- var isAjax = Request.IsAjaxRequest();
- // Do something about it.
- }
- [AjaxOnly]
- public ActionResult YourActionName()
- {
- // Omitted for brevity
- }
- public class AjaxOnlyAttribute : ActionFilterAttribute
- {
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- if (!filterContext.HttpContext.Request.IsAjaxRequest())
- {
- filterContext.Result = new HttpNotFoundResult();
- }
- }
- }
[AjaxOnly] within MVC6
The IsAjaxRequest() actually works by simply performing a check for the X-Requested-With header, as seen in the actual implementation of the function from MVC5.
- public static bool IsAjaxRequest(this HttpRequestBase request)
- {
- if (request == null)
- throw new ArgumentNullException("request");
- if (request["X-Requested-With"] == "XMLHttpRequest")
- return true;
- if (request.Headers != null)
- return request.Headers["X-Requested-With"] == "XMLHttpRequest";
- return false;
- }
- public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
- {
- public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
- {
- return routeContext.HttpContext.Request?.Headers["X-Requested-With"] == "XMLHttpRequest";
- }
- }

Bhavik PatelPosted Jul 14, 2016, 12:29 PM
Useful
Ravi KandelPosted Jul 14, 2016, 11:56 AM
Thanks for sharing.
kalu singh raoPosted Jul 14, 2016, 1:29 AM
Nice...