Request信息收集
在Controller的Action之中,Rails提供了一些方法可以让你得知此request各种信息,包括:
· action_name 目前的Action名称
· cookies Cookie下述
· headers HTTP标头
· params 包含用户所有传进来的参数Hash,这是最常使用的信息
· request 各种关于此request的详细信息
· request_method
· method
· delete?, get?, head?,post?, put?
· xml_http_request? 或 xhr?
· url
· protocol, host, port,path 和 query_string
· domain
· host_with_port
· port_string
· ssl?
· remote_ip?
· path_without_extension,path_without_format_and_extension, format_and_extension, relative_path
· env
· accepts
· format
· mime_type
· content_type
· headers
· body
· content_length
· response 代表要回传的内容,会由Rails设定好。通常你会用到的时机是你想加特别的Response Header。
· session Session下述
正确的说,params这个Hash是ActiveSupport::HashWithIndifferentAccess
对象,而不是普通的Hash而已。Ruby内建的Hash,用Symbol的hash[:foo]
和用字符串的hash["foo"]
是不一样的,这在混用的时候常常搞错而取不到值,算是常见的臭虫来源。Rails在这里使用的ActiveSupport::HashWithIndifferentAccess
对象,无论键是Symbol或字符串,都指涉相同的值,减少麻烦
取得域名 :
取得子域名:
取得主机名:
取得带端口的主机名:
代理服务器的主机名和端口:
取得由raw_host_with_port()获得的端口数值
取得raw_host_with_port()获得的端口文本字符串
取得当前使用网络协议
取得网络协议
request请求的uri地址
取得由env['SERVER_PORT']返回的端口值
当前是否在是用https加密协议
返回网络协议标准端口(http为80, https为443)
判断当前协议是否是标准端口
取得当前requset完整url
获取客户端ip
实例:(payments_controller.rb中)
def wechat_prepay
@order = current_user.orders.find_by_number(params[:number])
res = @order.wechat_prepay_id(request.remote_ip)
render json: res
end
def wechatpay_notify
result = Hash.from_xml(request.body.read)["xml"]
notify_params = result
@result_code = "FAILED"
ActiveRecord::Base.transaction do
notify_params = notify_params.symbolize_keys
if WxPay::Sign.verify?(notify_params)
Payment.get_pay("wechatpay", notify_params)
@result_code = "SUCCESS"
else
raise "wechatpay verify failed"
end
end
respond_to do |format|
format.xml
end
end