controller中request变量的用法

来源:互联网 发布:淘宝黑刷干货 编辑:程序博客网 时间:2024/06/14 05:28

Request信息收集

ControllerAction之中,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这个HashActiveSupport::HashWithIndifferentAccess对象,而不是普通的Hash而已。Ruby内建的Hash,用Symbolhash[:foo]和用字符串的hash["foo"]是不一样的,这在混用的时候常常搞错而取不到值,算是常见的臭虫来源。Rails在这里使用的ActiveSupport::HashWithIndifferentAccess对象,无论键是Symbol或字符串,都指涉相同的值,减少麻烦


取得域名 :
    request.domain #=>  zool.it request.domain(2) #=> blog.zool.it

取得子域名:
    request.subdomain #=>  "test.blog" request.subdomain(2) #=> "test"
    request.subdomain #=>  ["test", "blog"] request.subdomain(2) #=> ["test"]

取得主机名:
    request.host #=> "test.blog.zool.it"

取得带端口的主机名:
    request.host_with_port #=> "test.blog.zool.it:3000"

代理服务器的主机名和端口:
    request.raw_host_with_port #=> "test.blog.zool.it:3000"

取得由raw_host_with_port()获得的端口数值
    request.port #=> 3000

取得raw_host_with_port()获得的端口文本字符串
    request.port_string #=> ":3000"

取得当前使用网络协议
    request.protocol #=> "http://"

取得网络协议
    request.scheme #=> "http"

request请求的uri地址
    request.request_uri #=> "/posts/Hello-World"

取得由env['SERVER_PORT']返回的端口值
    request.server_port #=> "3000"

当前是否在是用https加密协议
    request.ssl?() #=> false

返回网络协议标准端口(http为80, https为443)
    request.standard_port #=> 80

判断当前协议是否是标准端口
    request.standard_port? #=> false

取得当前requset完整url
    request.url #=> "http://test.blog.zool.it:3000/posts/Hello-World"

获取客户端ip
   request.remote_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

0 1
原创粉丝点击