ASP.NET Core 判斷請求是否為Ajax請求
本文轉(zhuǎn)載自微信公眾號「UP技術(shù)控」,作者conan5566。轉(zhuǎn)載本文請聯(lián)系UP技術(shù)控公眾號。
概述
在寫后臺程序時,有時候需要知道客戶端發(fā)送的是普通的請求,還是ajax 請求,最近在做項(xiàng)目的時候,有些地方需要判斷當(dāng)前的請求是不是ajax。特地找了下發(fā)現(xiàn),jQuery 發(fā)出 ajax 請求時,會在請求頭部添加一個名為 X-Requested-With 的信息,信息內(nèi)容為:XMLHttpRequest。Ajax請求的request headers里都會有一個key為x-requested-with,值為XMLHttpRequest的header,所以我們就可以使用這個特性進(jìn)行判斷。
判斷是不是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;
- }
- }
- }