概述
在写后台程序时,有时候需要知道客户端发送的是普通的请求,还是ajax 请求,最近在做项目的时候,有些地方需要判断当前的请求是不是ajax。特地找了下发现,jQuery 发出 ajax 请求时,会在请求头部添加一个名为 X-Requested-With 的信息,信息内容为:XMLHttpRequest。Ajax请求的request headers里都会有一个key为x-requested-with,值为XMLHttpRequest的header,所以我们就可以使用这个特性进行判断。
判断是不是ajax
using System;namespace CompanyName.ProjectName.Web.Host.Framework
{public static class RequestExt{/// <summary>/// Determines whether the specified HTTP request is an AJAX request./// </summary>////// <returns>/// true if the specified HTTP request is an AJAX request; otherwise, false./// </returns>/// <param name="request">The HTTP request.</param>/// <exception cref="T:System.ArgumentNullException">/// The <paramref name="request"/>/// parameter is null (Nothing in Visual Basic).</exception>public static bool IsAjaxRequest(this Microsoft.AspNetCore.Http.HttpRequest request){if (request == null)throw new ArgumentNullException("request");if (request.Headers != null)return request.Headers["X-Requested-With"] == "XMLHttpRequest";return false;}}
}
控制ajax才能使用方法
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;namespace CompanyName.ProjectName.Web.Host.Framework
{public class AjaxOnlyAttribute : ActionMethodSelectorAttribute{public bool Ignore { get; set; }public AjaxOnlyAttribute(bool ignore = false){Ignore = ignore;}public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action){if (Ignore)return true;var request = routeContext.HttpContext.Request;if (request != null && request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest")return true;return false;}}
}