到目前为止,我已经找到了两种方法 request.format.json?
在Rails中是真的(即传入的请求被视为JSON)。一种是如果您请求资源并以结尾 .json
另一种是如果你提供标题 Accept: application/json
在你的请求中。每件作品都是独立的。
我想为第二种情况注册我自己的“接受”类型:
Accept: application/vnd.myapp_v1+json
并把它作为一个“json请求”像rails一样对待 application/json
,无需追加 .json
。
我的第一个想法是将我自己的MimeType注册为 :json
(在我的初始化代码中),但这实际上会破坏对application / json的支持,而不是我想要做的事情。
Mime::Type.register "application/vnd.myapp_v1+json", :json # my failed attempt
我们在我们的应用程序中使用before_filter将iPhone请求移动到HTML,如下所示:
before_filter :determine_format
def determine_format
request.format = :iphone if (request.env["HTTP_USER_AGENT"] =~ /iPhone/ && request.format == :html)
end
我想你可以用你的特定格式做类似的事情,也许是这样的:
def determine_format
request.format = :json if (request.format == 'application/vnd.myapp_v1+json')
end
我们在我们的应用程序中使用before_filter将iPhone请求移动到HTML,如下所示:
before_filter :determine_format
def determine_format
request.format = :iphone if (request.env["HTTP_USER_AGENT"] =~ /iPhone/ && request.format == :html)
end
我想你可以用你的特定格式做类似的事情,也许是这样的:
def determine_format
request.format = :json if (request.format == 'application/vnd.myapp_v1+json')
end
另一种方法是:
api_mime_types = %W(
application/vnd.api+json
text/x-json
application/json
)
Mime::Type.unregister :json
Mime::Type.register 'application/json', :json, api_mime_types
在 initializers/mime_types.rb
。