ruby-on-rails - rails : Restrict API requests to J

我想限制对所有 API Controller 的请求被重定向到 JSON 路径。我想使用重定向,因为 URL 也应该根据响应而改变。
一种选择是使用 before_filter 将请求重定向到相同的操作,但强制使用 JSON 格式。该示例尚未运行!

# base_controller.rb
class Api::V1::BaseController < InheritedResources::Base
  before_filter :force_response_format
  respond_to :json
  def force_response_format
    redirect_to, params[:format] = :json
  end
end

另一种选择是在路由设置中限制格式。

# routes.rb
MyApp::Application.routes.draw do
  namespace :api, defaults: { format: 'json' } do
    namespace :v1 do
      resources :posts
    end
  end
end

我希望所有请求都以 JSON 请求的形式结束:

http://localhost:3000/api/v1/posts
http://localhost:3000/api/v1/posts.html
http://localhost:3000/api/v1/posts.xml
http://localhost:3000/api/v1/posts.json
...

您会推荐哪种策略?

最佳答案

在您的路由中设置默认值不会将所有请求都转换为 JSON 请求。

您想要确保呈现的内容是 JSON 响应

除了你需要这样做之外,你几乎在第一个选项中就有了它

before_filter :set_default_response_format

private
  def set_default_response_format
    request.format = :json
  end

这将在您的 Base API Controller 下进行,因此当您执行实际操作时,格式将始终为 JSON。

关于ruby-on-rails - rails : Restrict API requests to JSON format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14664049/

相关文章:

json - Swift 4 JSON Decodable 解码类型更改的最简单方法

c# - 如何从 JObject 中按键获取值?

javascript - 通过 JSON 发送 64 位值的公认方式是什么?

json - 处理 HTTP 请求正文中的可选 JSON 字段

javascript - 通过 Angular 资源服务读取 JSON

java - 对 kotlin 数据类使用 Jackson @JsonProperty 注释

javascript - DRYing JSON 有什么众所周知的方法吗

java - 将 Gson 与接口(interface)类型一起使用

json - 在 Ubuntu 上将 jq 升级到 1.5

python - 将 JSON 模式转换为 python 类