Rails:如何将替代的Accept:内容类型视为JSON? [英] Rails: how to treat alternative Accept: content-types as JSON?
问题描述
到目前为止,我已经找到两种方法使 request.format.json?
在Rails中正确(即,将传入请求视为JSON)。一种是如果您请求资源并以 .json
结尾,另一种是如果您提供标头 Accept:application / json
在您的请求中。每个工作都是独立的。
So far I've found two ways for request.format.json?
to be true in Rails (i.e. where the incoming request is treated as JSON). One is if you request a resource and ending in .json
the other is if you supply the header Accept: application/json
in your request. Each work stand-alone.
对于第二种情况,我想注册自己的接受类型:
I want to register my own "accepts" type for this second case:
接受:application / vnd.myapp_v1 + json
,并将其像 $code> application一样被rails视为 json请求 / json ,而无需附加 .json
。
我的第一个想法是将我自己的MimeType注册为:json
(在我的初始化代码内),但这实际上会破坏对application / json的支持,而不是我想做的。
My first thought was to register my own MimeType as :json
(within my initialisation code), but this will actually break support for application/json, not what I want to do.
Mime::Type.register "application/vnd.myapp_v1+json", :json # my failed attempt
推荐答案
我们使用以下before_filter将iPhone请求移至应用中的HTML:
We move iPhone requests over to HTML in our app with a before_filter like so:
before_filter :determine_format
def determine_format
request.format = :iphone if (request.env["HTTP_USER_AGENT"] =~ /iPhone/ && request.format == :html)
end
我想您可以使用特定格式执行类似的操作,也许是这样的:
I imagine you can do something similar with your specific format, maybe like this:
def determine_format
request.format = :json if (request.format == 'application/vnd.myapp_v1+json')
end
这篇关于Rails:如何将替代的Accept:内容类型视为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!