我在我的应用程序中实现了一个简单的API来与Android应用程序通信。我尝试使用AbstractController::Metal主要是为了提高性能。我遇到的问题是render忽略了我传递的status选项。
非常简单的例子:
class Api::V1::ApiController < ActionController::Metal
include AbstractController::Rendering
include ActionController::Renderers::All
include ActionController::RackDelegation
include ActionController::MimeResponds
end
class Api::V1::SessionsController < Api::V1::ApiController
def show
render status: :unauthorized # using 401 yields the same result
end
end呼叫
curl -v -X GET http://app.dev:3000/api/v1/sessions.json我本希望得到一个401,但我得到的却是200 OK:
> GET /api/v1/sessions.json HTTP/1.1
> User-Agent: curl/7.30.0
> Host: app.dev:3000
> Accept: */*
>
< HTTP/1.1 200 OK有什么想法吗?到目前为止,覆盖response.status是我找到的唯一的解决办法,但老实说,它看起来像是一个丑陋的黑客。
提前感谢您的见解。
发布于 2016-01-24 22:30:05
要不渲染任何内容并返回代码401,请使用:
render nothing: true, status: :unauthorized发布于 2015-06-25 03:31:24
使用head ActionController::Head
class Api::V1::SessionsController < Api::V1::ApiController
def show
head :unauthorized
end
end发布于 2015-11-24 06:25:37
对于下面显示的示例代码,我也遇到了同样的问题。这是在Rails 3中使用ActionController::Metal,在升级到Rails 4.2.4后开始失败
# config/routes.rb
get :unauthorized, to: 'unauthorized#respond'
# app/controllers/unauthorized_controller.rb
class UnauthorizedController < ActionController::Metal
def respond
head :forbidden
end
end
# spec/controllers/unauthorized_controller_spec.rb
describe UnauthorizedController do
it 'should respond with 403 forbidden' do
get :respond, {}, {}
expect(response.status).to be == 403
end
end升级后测试失败。所以为了解决这个问题,我不得不改变
class UnauthorizedController < ActionController::Metal
至
class UnauthorizedController < ActionController::Base
https://stackoverflow.com/questions/25531441
复制相似问题