我实际上正在使用一个使用Rails 4的API.Content-Type如果客户端没有在Content-Type头文件中指定媒体类型,我想将请求设置为JSON .
为了获得该行为,我尝试before_action在我的添加中添加以下内容ApplicationController:
def set_request_default_content_type
request.format = :json
end
Run Code Online (Sandbox Code Playgroud)
在我的RegistrationsController#create方法中,我有一个断点来检查一切是否正常.好吧,request.format诀窍不起作用,尽管设置的值application/json似乎控制器(或Rails内部)不会将接收到的请求的Content-Type视为JSON.
我使用以下正文进行了POST请求(并且没有Content-Type):
{"user" : {"email":"foobar@mail.net","password":"foobarfoo"}}
Run Code Online (Sandbox Code Playgroud)
通过Pry调试我看到:
[2] api(#<V1::RegistrationsController>) _ request.format.to_s
=> "application/json"
[3] api(#<V1::RegistrationsController>) _ params
=> {
"action" => "create",
"controller" => "v1/registrations"
}
Run Code Online (Sandbox Code Playgroud)
这意味着Rails没有使用配置的request.format考虑我的请求Mime::JSON,而是使用Mime::ALL,因此它没有解析请求的JSON主体.:(
我的Rails 3网站受到具有奇怪接受标头的抓取工具的攻击,触发异常等
ActionView::MissingTemplate occurred in home#show
Run Code Online (Sandbox Code Playgroud)
以下是一些导致问题的接受标头
text/*
application/jxw
*/*;q=0.1
Run Code Online (Sandbox Code Playgroud)
在这些情况下,这被解释为请求的格式,因此导致丢失模板错误.我真的不在乎我回到这些抓取工具,但只是想避免异常.