在 Rails 中,如何像在 ASP 中那样访问 Request.ServerVariables?
我想访问给定的请求服务器变量,但我似乎无法在 Google 上找到任何有关如何访问请求对象的服务器变量的信息。 我该如何做到这一点,或者我注定永远不知道?
我为什么要这样做(但实际上不是我想做的事情)的一个例子:
用户登录,并且您想要存储他们登录位置的 IP 地址,或者我想记录他们正在查看该网站的浏览器的用户代理或引用者。
I want to access a given Requests ServerVariables, but I can't seem to find anything on Google on how to get access to the Server Vars of the request object. How do I do this or am I doomed to simply never know?
An example of why I'd want to do this (but not actually what I want to do):
User logs in, and you want to store the IP address of place where they logged in, or perhaps I want to record the user-agent or referer from the browser that they are viewing the site.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该查看控制器中可用的
request
对象。 有很多像request.remote_ip
这样的方法,您可以阅读有关 请求对象
You should look at the
request
object that's available from the controller. There are a bunch of methods likerequest.remote_ip
you can read more about the Request object on the Rails API site
控制器中的
request
访问器返回一个 ActionDispatch::Request 对象,该对象可以访问您期望的所有服务器变量。我找到的最佳文档在这里: http://apidock.com/rails/ v3.2.1/ActionDispatch/Request
有时您有其他答案中提到的诸如
request.remote_ip
之类的方法,其他时候您可以通过request.env
访问内容例如,要获取用户代理,请使用request.env["HTTP_USER_AGENT"]
The
request
accessor in a controller returns an ActionDispatch::Request object which can access all of the server variables you would expect.Best documentation I've found for it is here: http://apidock.com/rails/v3.2.1/ActionDispatch/Request
Sometimes you have methods like
request.remote_ip
as mentioned in the other answer, other times you can access things viarequest.env
, for example, to get the user agent, userequest.env["HTTP_USER_AGENT"]