在控制器上进行过滤以检查用户代理,然后根据结果是否为真进行重定向

如何解决在控制器上进行过滤以检查用户代理,然后根据结果是否为真进行重定向

---------注意(编辑)- 我可能做的是完全错误的,如果实际上是错误的(对mvc来说是新的)

在解决方案中,存在robots.txt文件来阻止该网站上的所有抓取工具。唯一的问题是,Facebook的抓取工具/抓取工具未遵循规则,仍在抓取/抓取网站,并导致每两分钟记录和发送电子邮件时出现错误。为此发送的错误是“在控制器'SolutionName.Web.Controllers.QuoteController'上找不到公共操作方法'Customer'。”

解决方案是在控制器上创建过滤器以检查代理名称。如果代理名称是针对Facebook的,则将其重定向到“无机器人认证页面”。过滤器必须位于控制器上,因为该站点提供3条不同的路由,其中​​的每条路由都有一个自定义链接,客户可以访问在Facebook上共享的直接链接(因此无法在路由配置中为此创建路由)。

我面临的问题是解决方案无法在控制器过滤器上立即重定向。它加入了Action方法(这些操作方法是Partial Pages),然后由于无法重定向而失败(然后该视图已经开始呈现-这是正确的)。 是否有一种方法在第一次访问此过滤器时立即重定向?还是有更好的解决方案?

要测试和解决故障,我正在更改代码中的用户代理以匹配记录的内容。 从过滤器重定向时发生错误:“不允许子操作执行重定向操作。”

由于Facebook的爬网程序而当前记录的错误:“在控制器'SolutionName.Web.Controllers.QuoteController'上未找到公共操作方法'Customer'。”

堆栈跟踪中的用户代理:

enter image description here

这就是我所做的:

自定义过滤器:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;

    namespace SolutionName.Web.Classes
    {
        public class UserAgentActionFilterAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                try
                {
                    List<string> Crawlers = new List<string>()
                    {
                        "facebookexternalhit/1.1","facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)","facebookexternalhit/1.1","Facebot"
                     };

                     string userAgent = HttpContext.Current.Request.UserAgent.ToLower();
                     bool iscrawler = Crawlers.Exists(x => userAgent.Contains(x));
                     if (userAgent != null && iscrawler)
                     {
                        filterContext.Result = new RedirectResult("~/Home/NoRobotsAuthentication");
                        return;
                     }
            
                    base.OnActionExecuting(filterContext);

                 }
                 catch (Exception errException)
                 {
                    LogHelper.LogException(Severity.Error,errException);
                    SessionHelper.PolicyBase = null;
                    SessionHelper.ClearQuoteSession();
                    filterContext.Result = new RedirectResult("~/Home/NoRobotsAuthentication");
                    return;
                }
            }
        }
    }

NoRobotsAuthentication.cshtml:

@{
        ViewBag.PageTitle = "Robots not authorized";
        Layout = "~/Views/Shared/_LayoutClean2.cshtml";
 }

 <div class="container body-content">
     <div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 container-solid">
        <div class="form-horizontal">
            <h3>@ViewBag.NotAuthorized</h3>
        </div>
    </div>
</div>

没有机器人的操作方法:

    #region Bot Detection
    public ActionResult NoRobotsAuthentication()
    {
        ViewBag.NotAuthorized = "Robots / Scrapers not authorized!";
        return View();
    }

    #endregion

我要检查的控制器之一:

    namespace SolutionName.Web.Controllers
    {
        [UserAgentActionFilter]
        public class QuoteController : Controller
        {

            public ActionResult Customer()
            { //Some logic }
        }
    }

部分页面操作结果,在运行过滤器时发生错误:

    public ActionResult _Sidebar()
    {
        var model = SessionHelper.PolicyBase;
        return PartialView("_Sidebar",model);
    }

解决方法

这是因为您使用的是ActionFilterAttribute。如果您在此处查看文档:{​​{3}},它说明了过滤器的生命周期,并且基本上-到您到达动作过滤器时,为时已晚。您需要授权过滤器或资源过滤器,以使请求短路。

每种过滤器类型在过滤器的不同阶段执行 管道:

授权过滤器

  • 授权过滤器首先运行,用于确定用户是否获得请求授权。
  • 如果请求未被授权,授权过滤器将使管道短路。

资源过滤器

  • 授权后运行。
  • OnResourceExecuting在其余过滤器管道之前运行代码。例如,OnResourceExecuting在模型绑定之前运行代码。
  • OnResourceExecuted在其余部分之后运行代码 管道已经完成。

以下示例摘自文档,它是资源过滤器的实现。大概可以通过授权过滤器实现类似的实现,但是我认为在授权过滤器失败后返回有效的Http状态代码可能有点反模式。

// See that it's implementing IResourceFilter
public class ShortCircuitingResourceFilterAttribute : Attribute,IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.Result = new ContentResult()
        {
            Content = "Resource unavailable - header not set."
        };
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

我试图将其与您提供的内容合并-请注意,这可能开箱即用。

public class ShortCircuitingResourceFilterAttribute : Attribute,IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        try
        {
            // You had duplicates in your list,try to use Hashset for .Contains methods
            var crawlerSet = new Hashset<string>()
            {
               "facebookexternalhit/1.1","facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)","Facebot"
            };
                    
            string userAgent = HttpContext.Current.Request.UserAgent;
            // You're unnecessarily and incorrectly checking if the userAgent is null multiple times
            // if it's null it'll fail when you're .ToLower()'ing it. 
            if (!string.IsNullOrEmpty(userAgent) && crawlerSet.Contains(userAgent.ToLower()))
            {
                // Some crawler
                context.Result = new RedirectResult("~/Home/NoRobotsAuthentication");
            }
         }
         catch (Exception errException)
         {
            LogHelper.LogException(Severity.Error,errException);
            SessionHelper.PolicyBase = null;
            SessionHelper.ClearQuoteSession();
            context.Result = new RedirectResult("~/Home/NoRobotsAuthentication");
         }
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-