您现在的位置是:亿华云 > 数据库

ASP.NET Core 判断请求是否为Ajax请求

亿华云2025-10-03 13:59:19【数据库】6人已围观

简介本文转载自微信公众号「UP技术控」,作者conan5566。转载本文请联系UP技术控公众号。概述在写后台程序时,有时候需要知道客户端发送的是普通的请求,还是ajax 请求,最近在做项目的时候,有些地方

 

本文转载自微信公众号「UP技术控」,判断作者conan5566。请求请求转载本文请联系UP技术控公众号。判断

概述

在写后台程序时,请求请求有时候需要知道客户端发送的判断是普通的请求,还是请求请求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;         }     } } 

很赞哦!(731)