在ASP.NET Core 中通过 ActionFilterAttribute 实现蜘蛛访问拦截

环境:ASP.NET Core 2.1 

前提:由于前端页面调用接口的方式

$(document).ready(function () {
    var ID = getZxId();
    $.ajax({
        type: "post",
        xhrFields: { withCredentials: true },
        crossDomain: true,
        url: "https://wlpageview.chinawutong.com/pageView/id",
        dataType: "json",
        data: {
            id: ID
        },
        success: function (res) {
            //console.log(res)
        }
    });
});

思路:导致的问题,搜索引擎抓取页面也会执行接口调用,如何实现阻止接口被搜素引擎调用了?

方法:在后台通过实现ActionFilterAttribute 过滤器,对UA头进行验证,如果是蜘蛛访问,则直接返回

步骤:1、实现ActionFilterAttribute过滤器,并且对UA头进行验证

  /// <summary>
    /// 网站蜘蛛访问拦截
    /// </summary>
    public class UserAgentCheck_FilterAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["User-Agent"]))
            {
                filterContext.Result = new JsonResult(ResponseModel.Failed(HttpStatusCode.Forbidden.ToString(), "访问异常!"));
            }
            string userAgent = filterContext.HttpContext.Request.Headers["User-Agent"].ToString().ToLower();

            if (userAgent.IndexOf("googleboot") > -1 || userAgent.IndexOf("spider") > -1)
            {
                filterContext.Result = new JsonResult(ResponseModel.Failed(HttpStatusCode.OK.ToString(), "spider访问!"));
            }
        }
    }

2、在需要做拦截的Action方法上面加入特性

原文地址:https://www.cnblogs.com/Learnall/p/14344181.html