[英]Rails Action Cable: How to fetch User Agent & Client IP Address?
I am upgrading a Rails app to use websocket via Action Cable.我正在升级 Rails 应用程序以通过 Action Cable 使用 websocket。 For logging purposes, I need to get the client's IP address and the user agent who sends the socket message.
出于日志记录的目的,我需要获取客户端的 IP 地址和发送套接字消息的用户代理。
In the speak
method of MyChannel
class ( app/channels/my_channel.rb
), I cannot access the session or the request.在
MyChannel
类( app/channels/my_channel.rb
)的speak
方法中,我无法访问会话或请求。
Do you have any idea on how I can get user_agent
and the client IP address in this speak
method?您对我如何在此
speak
方法中获取user_agent
和客户端 IP 地址有任何想法吗?
您可以从 Channel 所属的 Connection 对象中的请求中获取此信息。
ActionCable::Connection::Base
contains all information about the current connection environment (HTTP headers, rack process, etc), and you can access it via its env
attribute reader. ActionCable::Connection::Base
包含有关当前连接环境的所有信息(HTTP 标头、机架进程等),您可以通过其env
属性读取器访问它。
For example, here is how I get the User-Agent HTTP header which was used while establishing WebSocket connection:例如,这里是我如何获取在建立 WebSocket 连接时使用的User-Agent HTTP 标头:
user_agent = connection.env["HTTP_USER_AGENT"]
Note that I run this code from ApplicationCable::Channel
instance, where connection instance is available via connection
attribute请注意,我从
ApplicationCable::Channel
实例运行此代码,其中连接实例可通过connection
属性获得
I couldn't find any documentation about it, but I believe it's safe since env
attribute is made publicly available ( https://api.rubyonrails.org/v5.1.6/classes/ActionCable/Connection/Base.html#method-i-request ).我找不到任何关于它的文档,但我相信它是安全的,因为
env
属性是公开可用的( https://api.rubyonrails.org/v5.1.6/classes/ActionCable/Connection/Base.html#method-i -请求)。 You can get the full list of the keys that this hash contains by running connection.env.keys
in console (when connection
instance is available, obviously).您可以通过在控制台中运行
connection.env.keys
来获取此哈希包含的键的完整列表(显然,当connection
实例可用时)。
要使用remote_ip
助手,您可以在您的频道中执行此操作:
ActionDispatch::Request.new(connection.env).remote_ip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.