首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 4 AbstractController::Metal rendering with status != 200 (即401,404)

Rails 4 AbstractController::Metal rendering with status != 200 (即401,404)
EN

Stack Overflow用户
提问于 2014-08-27 23:40:17
回答 3查看 901关注 0票数 10

我在我的应用程序中实现了一个简单的API来与Android应用程序通信。我尝试使用AbstractController::Metal主要是为了提高性能。我遇到的问题是render忽略了我传递的status选项。

非常简单的例子:

代码语言:javascript
复制
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

呼叫

代码语言:javascript
复制
curl -v -X GET http://app.dev:3000/api/v1/sessions.json

我本希望得到一个401,但我得到的却是200 OK:

代码语言:javascript
复制
> 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是我找到的唯一的解决办法,但老实说,它看起来像是一个丑陋的黑客。

提前感谢您的见解。

EN

回答 3

Stack Overflow用户

发布于 2016-01-24 22:30:05

要不渲染任何内容并返回代码401,请使用:

代码语言:javascript
复制
render nothing: true, status: :unauthorized
票数 1
EN

Stack Overflow用户

发布于 2015-06-25 03:31:24

使用head ActionController::Head

代码语言:javascript
复制
class Api::V1::SessionsController < Api::V1::ApiController
  def show
    head :unauthorized
  end
end
票数 0
EN

Stack Overflow用户

发布于 2015-11-24 06:25:37

对于下面显示的示例代码,我也遇到了同样的问题。这是在Rails 3中使用ActionController::Metal,在升级到Rails 4.2.4后开始失败

代码语言:javascript
复制
# 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25531441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档