【问题标题】:Check for the existing of a header attribute in rails before invoking an action在调用操作之前检查 rails 中是否存在标头属性
【发布时间】:2017-06-19 22:39:59
【问题描述】:

我正在 Rails 4 中构建 API。在调用操作之前,我首先尝试检查 http 标头中是否存在属性。有没有办法做到这一点,而不是检查每个控制器的所有操作。 rails 文档提到了类似

constraints(lambda { |req| req.env["HTTP_CUSTOM_HEADER"] =~ /value/ }) do
  #controller, action mapping
end

但我仍然想给使用我的 API 的用户一个反馈。类似于发送带有消息的 json 声明:missing the custom attribute in the header

【问题讨论】:

    标签: ruby-on-rails ruby rails-routing ruby-on-rails-4.2


    【解决方案1】:

    您可以在控制器中添加before_action,并检查一个header属性,例如:

    class SomeController < ApplicationController
      before_action :render_message, unless: :check_header
    
      def check_header
        request.env["HTTP_CUSTOM_HEADER"] =~ /foo/
      end
    
      def render_message
        render json: { message: "missing the custom attribute in the header" }
      end
    end
    

    如果check_attribute 过滤器返回nil,则render_message 操作会呈现所需的消息。

    【讨论】:

    • 我有很多控制器,我不想在每个控制器中都使用它。我基本上有 4 个控制器,每个控制器都必须进行此检查
    • 好的,谢谢,我认为将您的代码添加到动作控制器将完美运行。谢谢你的灵感:)
    【解决方案2】:

    您可以使用before_action 过滤器检查控制器操作:

    例如在APIController:

    class APIController < ApplicationController
      before_action :check_headers
    
      private
    
      def check_header
        # do whatever is required here
      end
    end
    

    【讨论】:

      【解决方案3】:

      如果标头的存在充当身份验证机制,则没有必要为此打后端,请尝试在反向代理端更早地避免它:

      nginx.conf

      server {
        location / {
          if ($http_x_custom_header) {
            return 200 'missing the custom attribute in the header'; 
          }
          proxy_pass...
        }
      }
      

      【讨论】:

      • 好吧,因为我正在为此构建一个 api,所以我不想这样做,因为 api 可能会在下一个版本中发生变化。我仍然想完全控制我的代码库
      • 好的,如果它的行为超出简单检查并且以后可能会更改,那么在应用层进行标头检测是有意义的
      猜你喜欢
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      相关资源
      最近更新 更多