【问题标题】:Rails: how to treat alternative Accept: content-types as JSON?Rails:如何将替代接受:内容类型视为 JSON?
【发布时间】:2012-02-22 01:48:39
【问题描述】:

到目前为止,我已经找到了两种方法让 request.format.json? 在 Rails 中为真(即传入请求被视为 JSON)。一种是如果您请求资源并以.json 结尾,另一种是如果您在请求中提供标头Accept: application/json。每个作品都是独立的。

我想为第二种情况注册我自己的“接受”类型:

Accept: application/vnd.myapp_v1+json 并让 Rails 将其视为像 application/json 一样的“json 请求”,而无需附加 .json

我的第一个想法是将我自己的 MimeType 注册为 :json(在我的初始化代码中),但这实际上会破坏对 application/json 的支持,而不是我想要做的。

    Mime::Type.register "application/vnd.myapp_v1+json", :json  # my failed attempt

【问题讨论】:

    标签: ruby-on-rails content-type


    【解决方案1】:

    另一种方法是:

    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

    【讨论】:

      【解决方案2】:

      我们在应用中使用 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
      

      【讨论】:

        猜你喜欢
        • 2015-04-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2012-09-22
        • 2011-12-24
        • 2020-08-13
        • 1970-01-01
        • 2019-01-21
        相关资源
        最近更新 更多