您当前的位置: 首页 >  ajax

Linux小百科

暂无认证

  • 0浏览

    0关注

    1185博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

判断请求是否为Ajax请求的小妙招

Linux小百科 发布时间:2021-12-17 10:03:48 ,浏览量:0

在写后台程序时,有时候需要知道客户端发送的是普通的请求,还是ajax 请求,最近在做项目的时候,有些地方需要判断当前的请求是不是ajax。

概述

在写后台程序时,有时候需要知道客户端发送的是普通的请求,还是ajax 请求,最近在做项目的时候,有些地方需要判断当前的请求是不是ajax。特地找了下发现,jQuery 发出 ajax 请求时,会在请求头部添加一个名为 X-Requested-With 的信息,信息内容为:XMLHttpRequest。Ajax请求的request headers里都会有一个key为x-requested-with,值为XMLHttpRequest的header,所以我们就可以使用这个特性进行判断。

判断请求是否为Ajax请求的小妙招判断请求是否为Ajax请求的小妙招

判断是不是ajax

using System; 
 
namespace CompanyName.ProjectName.Web.Host.Framework 
{ 
    public static class RequestExt 
    { 
        /// 

/// Determines whether the specified HTTP request is an AJAX request. /// /// /// /// true if the specified HTTP request is an AJAX request; otherwise, false. /// /// The HTTP request. /// /// The /// parameter is null (Nothing in Visual Basic). 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; 
        } 
    } 
} 

 

关注
打赏
1665632672
查看更多评论
立即登录/注册

微信扫码登录

0.0520s