класс ActionDispatch::Request
Константы
- ENV_METHODS
- HTTP_METHODS
- HTTP_METHOD_LOOKUP
- LOCALHOST
- RFC2518
-
HTTP-методы из RFC 2518: HTTP Extensions for Distributed Authoring – WEBDAV
- RFC2616
-
HTTP-методы из RFC 2616: Hypertext Transfer Protocol – HTTP/1.1
- RFC3253
-
HTTP-методы из RFC 3253: Versioning Extensions to WebDAV
- RFC3648
-
HTTP-методы из RFC 3648: WebDAV Ordered Collections Protocol
- RFC3744
-
HTTP-методы из RFC 3744: WebDAV Access Control Protocol
- RFC4791
-
HTTP-методы из RFC 4791: Calendaring Extensions to WebDAV
- RFC5323
-
HTTP-методы из RFC 5323: WebDAV SEARCH
- RFC5789
-
HTTP-методы из RFC 5789: PATCH Method for HTTP
Атрибуты
Открытые методы класса
# File actionpack/lib/action_dispatch/http/request.rb, line 60
def self.empty
new({})
end # File actionpack/lib/action_dispatch/http/request.rb, line 64 def initialize(env) super @rack_request = Rack::Request.new(env) @method = nil @request_method = nil @remote_ip = nil @original_fullpath = nil @fullpath = nil @ip = nil end
ActionDispatch::Http::URL::new Общедоступные методы экземпляров
# File actionpack/lib/action_dispatch/http/request.rb, line 394
def GET
fetch_header("action_dispatch.request.query_parameters") do |k|
encoding_template = Request::Utils::CustomParamEncoder.action_encoding_template(self, path_parameters[:controller], path_parameters[:action])
rack_query_params = ActionDispatch::ParamBuilder.from_query_string(rack_request.query_string, encoding_template: encoding_template)
set_header k, rack_query_params
end
rescue ActionDispatch::ParamError => e
raise ActionController::BadRequest.new("Invalid query parameters: #{e.message}")
end Переопределяет метод GET фреймворка Rack для поддержки неразличимого доступа.
# File actionpack/lib/action_dispatch/http/request.rb, line 407
def POST
fetch_header("action_dispatch.request.request_parameters") do
encoding_template = Request::Utils::CustomParamEncoder.action_encoding_template(self, path_parameters[:controller], path_parameters[:action])
param_list = nil
pr = parse_formatted_parameters(params_parsers) do
if param_list = request_parameters_list
ActionDispatch::ParamBuilder.from_pairs(param_list, encoding_template: encoding_template)
else
# We're not using a version of Rack that provides raw form
# pairs; we must use its hash (and thus post-process it below).
fallback_request_parameters
end
end
# If the request body was parsed by a custom parser like JSON
# (and thus the above block was not run), we need to
# post-process the result hash.
if param_list.nil?
pr = ActionDispatch::ParamBuilder.from_hash(pr, encoding_template: encoding_template)
end
self.request_parameters = pr
end
rescue ActionDispatch::ParamError, EOFError => e
raise ActionController::BadRequest.new("Invalid request parameters: #{e.message}")
end Переопределяет метод POST фреймворка Rack для поддержки неразличимого доступа.
# File actionpack/lib/action_dispatch/http/request.rb, line 459
def authorization
get_header("HTTP_AUTHORIZATION") ||
get_header("X-HTTP_AUTHORIZATION") ||
get_header("X_HTTP_AUTHORIZATION") ||
get_header("REDIRECT_X_HTTP_AUTHORIZATION")
end Возвращает заголовок авторизации независимо от того, был ли он указан напрямую или через один из альтернативных прокси.
# File actionpack/lib/action_dispatch/http/request.rb, line 356
def body
if raw_post = get_header("RAW_POST_DATA")
raw_post = (+raw_post).force_encoding(Encoding::BINARY)
StringIO.new(raw_post)
else
body_stream
end
end Тело запроса — это потоковый ввод IO. Если переменная среды RAW_POST_DATA уже задана, оберните её в StringIO.
# File actionpack/lib/action_dispatch/http/request.rb, line 491 def commit_csrf_token controller_instance.commit_csrf_token(self) if controller_instance.respond_to?(:commit_csrf_token) end
# File actionpack/lib/action_dispatch/http/request.rb, line 480 def commit_flash end
# File actionpack/lib/action_dispatch/http/request.rb, line 291 def content_length return raw_post.bytesize if has_header?(TRANSFER_ENCODING) super.to_i end
Возвращает длину тела запроса в виде целого числа.
# File actionpack/lib/action_dispatch/http/request.rb, line 88 def controller_class params = path_parameters params[:action] ||= "index" controller_class_for(params[:controller]) end
# File actionpack/lib/action_dispatch/http/request.rb, line 94
def controller_class_for(name)
if name
controller_param = name.underscore
const_name = controller_param.camelize << "Controller"
begin
const_name.constantize
rescue NameError => error
if error.missing_name == const_name || const_name.start_with?("#{error.missing_name}::")
raise MissingController.new(error.message, error.name)
else
raise
end
end
else
PASS_NOT_FOUND
end
end # File actionpack/lib/action_dispatch/http/request.rb, line 372 def form_data? FORM_DATA_MEDIA_TYPES.include?(media_type) end
Определяет, содержит ли тело запроса данные формы, проверяя запрос Content-Type на соответствие одному из типов медиа: application/x-www-form-urlencoded или multipart/form-data. Список типов медиа данных формы можно изменить через массив FORM_DATA_MEDIA_TYPES.
Предполагается, что тело запроса не содержит данных формы, когда не указан заголовок Content-Type и request_method равен POST.
# File actionpack/lib/action_dispatch/http/request.rb, line 270 def fullpath @fullpath ||= super end
Возвращает полную String путь с параметрами последнего запрошенного URL.
# get "/articles" request.fullpath # => "/articles" # get "/articles?page=2" request.fullpath # => "/articles?page=2"
# File actionpack/lib/action_dispatch/http/request.rb, line 232 def headers @headers ||= Http::Headers.new(self) end
Обеспечивает доступ к HTTP-заголовкам запроса, например:
request.headers["Content-Type"] # => "text/plain"
# File actionpack/lib/action_dispatch/http/request.rb, line 198 def http_auth_salt get_header "action_dispatch.http_auth_salt" end
# File actionpack/lib/action_dispatch/http/request.rb, line 305 def ip @ip ||= super end
Возвращает IP-адрес клиента в виде String.
# File actionpack/lib/action_dispatch/http/request.rb, line 115 def key?(key) has_header? key end
Возвращает true, если запрос имеет заголовок, соответствующий заданному параметру key.
request.key? :ip_spoofing_check # => true
# File actionpack/lib/action_dispatch/http/request.rb, line 467 def local? LOCALHOST.match?(remote_addr) && LOCALHOST.match?(remote_ip) end
True, если запрос пришёл с localhost, 127.0.0.1 или ::1.
# File actionpack/lib/action_dispatch/http/request.rb, line 476
def logger
get_header("action_dispatch.logger")
end # File actionpack/lib/action_dispatch/http/request.rb, line 286 def media_type content_mime_type&.to_s end
Тип MIME запроса.
# get "/articles" request.media_type # => "application/x-www-form-urlencoded"
# File actionpack/lib/action_dispatch/http/request.rb, line 212
def method(*args)
if args.empty?
@method ||= check_method(
get_header("rack.methodoverride.original_method") ||
get_header("REQUEST_METHOD")
)
else
super
end
end Возвращает исходное значение REQUEST_METHOD из окружения, даже если оно было переопределено средством. См. request_method для получения дополнительной информации.
В целях отладки, при вызове с аргументами, этот метод обратится к Object#method.
# File actionpack/lib/action_dispatch/http/request.rb, line 225 def method_symbol HTTP_METHOD_LOOKUP[method] end
Возвращает символическую форму method.
# File actionpack/lib/action_dispatch/http/request.rb, line 259
def original_fullpath
@original_fullpath ||= (get_header("ORIGINAL_FULLPATH") || fullpath)
end Возвращает String с последним запрошенным путём, включая параметры.
# get '/foo' request.original_fullpath # => '/foo' # get '/foo?bar' request.original_fullpath # => '/foo?bar'
# File actionpack/lib/action_dispatch/http/request.rb, line 278 def original_url base_url + original_fullpath end
Возвращает исходный URL запроса в виде String.
# get "/articles?page=2" request.original_url # => "http://www.example.com/articles?page=2"
# File actionpack/lib/action_dispatch/http/request.rb, line 347
def raw_post
unless has_header? "RAW_POST_DATA"
set_header("RAW_POST_DATA", read_body_stream)
end
get_header "RAW_POST_DATA"
end Чтение тела запроса. Это полезно для веб-сервисов, которым необходимо работать напрямую с сырыми запросами.
# File actionpack/lib/action_dispatch/http/request.rb, line 311
def remote_ip
@remote_ip ||= (get_header("action_dispatch.remote_ip") || ip).to_s
end Возвращает IP-адрес клиента в формате String, обычно устанавливаемый посредством middleware RemoteIp.
# File actionpack/lib/action_dispatch/http/request.rb, line 315 def remote_ip=(remote_ip) @remote_ip = nil set_header "action_dispatch.remote_ip", remote_ip end
# File actionpack/lib/action_dispatch/http/request.rb, line 330 def request_id get_header ACTION_DISPATCH_REQUEST_ID end
Возвращает уникальный идентификатор запроса, основанный на заголовке X-Request-Id, который может генерироваться брандмауэром, балансировщиком нагрузки или веб-сервером, или на middleware RequestId (который устанавливает переменную окружения action_dispatch.request_id).
Этот уникальный идентификатор полезен для отслеживания запроса от начала до конца в рамках ведения журнала или отладки. Это зависит от переменной Rack, установленной middleware ActionDispatch::RequestId.
# File actionpack/lib/action_dispatch/http/request.rb, line 152 def request_method @request_method ||= check_method(super) end
Возвращает HTTP-метод, который должен видеть приложение. В случае, если метод был переопределён middleware (например, если запрос HEAD был преобразован в GET, или если параметр _method был использован для определения метода, который должно использовать приложение), этот метод возвращает переопределённое значение, а не исходное.
# File actionpack/lib/action_dispatch/http/request.rb, line 203 def request_method_symbol HTTP_METHOD_LOOKUP[request_method] end
Возвращает символьное представление метода request_method.
# File actionpack/lib/action_dispatch/http/request.rb, line 471
def request_parameters=(params)
raise if params.nil?
set_header("action_dispatch.request.request_parameters", params)
end # File actionpack/lib/action_dispatch/http/request.rb, line 436
def request_parameters_list
# We don't use Rack's parse result, but we must call it so Rack
# can populate the rack.request.* keys we need.
rack_post = rack_request.POST
if form_pairs = get_header("rack.request.form_pairs")
# Multipart
form_pairs
elsif form_vars = get_header("rack.request.form_vars")
# URL-encoded
ActionDispatch::QueryParser.each_pair(form_vars)
elsif rack_post && !rack_post.empty?
# It was multipart, but Rack did not preserve a pair list
# (probably too old). Flat parameter list is not available.
nil
else
# No request body, or not a format Rack knows
[]
end
end # File actionpack/lib/action_dispatch/http/request.rb, line 487 def reset_csrf_token controller_instance.reset_csrf_token(self) if controller_instance.respond_to?(:reset_csrf_token) end
# File actionpack/lib/action_dispatch/http/request.rb, line 380 def reset_session session.destroy reset_csrf_token end
# File actionpack/lib/action_dispatch/http/request.rb, line 160
def route_uri_pattern
get_header("action_dispatch.route_uri_pattern")
end Возвращает шаблон URI сопоставленного маршрута для запроса, используя тот же формат, что и bin/rails routes:
request.route_uri_pattern # => "/:controller(/:action(/:id))(.:format)"
# File actionpack/lib/action_dispatch/http/request.rb, line 248 def send_early_hints(links) env["rack.early_hints"]&.call(links) end
Early Hints — это HTTP/2 код состояния, который указывает подсказки для подготовки клиента к обработке конечного ответа.
Если в окружении содержится rack.early_hints, сервер поддерживает HTTP2 push для заголовков ссылок.
Метод send_early_hints принимает хеш ссылок следующим образом:
send_early_hints("link" => "</style.css>; rel=preload; as=style,</script.js>; rel=preload")
Если вы используете javascript_include_tag или stylesheet_link_tag, заголовки Early Hints включаются по умолчанию, если поддерживаются.
# File actionpack/lib/action_dispatch/http/request.rb, line 341
def server_software
(get_header("SERVER_SOFTWARE") && /^([a-zA-Z]+)/ =~ get_header("SERVER_SOFTWARE")) ? $1.downcase : nil
end Возвращает имя программного обеспечения HTTP-сервера в нижнем регистре.
# File actionpack/lib/action_dispatch/http/request.rb, line 389 def session_options=(options) Session::Options.set self, options end
# File actionpack/lib/action_dispatch/http/request.rb, line 299
def xml_http_request?
/XMLHttpRequest/i.match?(get_header("HTTP_X_REQUESTED_WITH"))
end Возвращает true, если заголовок X-Requested-With содержит “XMLHttpRequest” (регистр не учитывается), что может потребоваться добавить вручную в зависимости от выбранных JavaScript библиотек и фреймворков.
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.