强制所有收到的请求内容类型为JSON [英] Force all received requests Content-Type to JSON
问题描述
实际上,我工作的,它使用的Rails 4.一个API,我想设置成JSON请求的内容类型
如果客户未指定媒体类型在内容类型
头。
为了得到这种行为我尝试添加以下 before_action
在我的的ApplicationController
:
高清set_request_default_content_type
request.format =:JSON
结束
在我的 RegistrationsController#创建
方法我有一个断点来检查,如果一切工作正常。那么, request.format
招不起作用,尽管值设置为应用程序/ JSON
似乎控制器(或Rails内部)不考虑接收到的请求的Content-Type为JSON。
我做了以下机身POST请求(没有内容类型):
{用户:{电子邮件:foobar@mail.net,密码:foobarfoo}}
通过与调试撬我看到:
[2] API(#< V1 :: RegistrationsController>)_ request.format.to_s
= GT; 应用/ JSON
[3] API(#< V1 :: RegistrationsController>)_ PARAMS
= GT; {
行动=> 创建,
控制器=> V1 /注册
}
这意味着Rails的没有考虑过我与配置request.format哑剧:: JSON
的要求,而是和默:: ALL
,所以它并没有解析请求的JSON身上。 (
类V1 :: RegistrationsController< ApplicationController中
respond_to代码:JSON
结束
使得默认格式效应初探JSON
I'm actually working on an API which uses Rails 4. I would like to set the Content-Type
of a request to JSON if the client does not specify a media type in Content-Type
header.
In order to get that behaviour I tried to add the following before_action
in my ApplicationController
:
def set_request_default_content_type
request.format = :json
end
In my RegistrationsController#create
method I have a breakpoint to check if everything is working. Well, the request.format
trick does not work, despite the value is set to application/json
it seems that the controller (or Rails internals) do not consider the received request's Content-Type as JSON.
I did a POST request with the following body (and no Content-Type) :
{"user" : {"email":"foobar@mail.net","password":"foobarfoo"}}
By debugging with Pry I see that :
[2] api(#<V1::RegistrationsController>) _ request.format.to_s
=> "application/json"
[3] api(#<V1::RegistrationsController>) _ params
=> {
"action" => "create",
"controller" => "v1/registrations"
}
It means that Rails did not have considered my request with the request.format configured with Mime::JSON
, but instead with Mime::ALL
and so it didn't parse the request's JSON body. :(
class V1::RegistrationsController < ApplicationController
respond_to :json
end
Makes the default reponse format json
这篇关于强制所有收到的请求内容类型为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!