【问题标题】:Return a specific http status code in Rails在 Rails 中返回特定的 http 状态码
【发布时间】:2012-02-12 00:06:38
【问题描述】:

如何在 Rails 中为整个应用程序返回 503 Service Unavailable

另外,你如何对特定的控制器做同样的事情?

【问题讨论】:

    标签: ruby-on-rails http http-status-codes http-status-code-503


    【解决方案1】:

    对于整个应用程序:

    # ApplicationController
    before_filter :return_unavailable_status
    
    private
      def return_unavailable_status
        render :nothing => true, :status => :service_unavailable
      end
    

    如果您想要自定义错误页面,您可以这样做:

    render 'custom_unavailable_page', :status => :service_unavailable    
    

    如果您不希望特定控制器使用它:

    # SomeController
    skip_before_filter :return_unavailable_status
    

    【讨论】:

    • 我应该使用render "custom_unavailable_page"而不是render :nothing => true来显示自定义的下页
    • @SathishManohar 没错。 custom_unavailable_page 将是您要渲染的视图文件的名称。
    • 记录在哪里?其他状态是什么? api.rubyonrails.org/classes/ActionView/Helpers/…
    • @Chloe 我不相信它的记录很好,但这里有一个列表apidock.com/rails/ActionController/Base/…
    • 弃用警告::nothing 选项已弃用,将在 Rails 5.1 中删除。使用head 方法以空响应体响应
    【解决方案2】:

    你可以使用head

    head 503
    # or
    head :service_unavailable
    

    【讨论】:

    • 我可以使用状态符号,例如 :service_unavailable 所有状态:apidock.com/rails/ActionController/Base/…
    • @freemanoid:我个人更喜欢整数代码。我已经认识他们了。无需记住另一组值。
    • 弃用警告::nothing 选项已弃用,将在 Rails 5.1 中删除。使用head 方法以空响应体响应
    • @SergioTulentsev 我只会更新答案以使用head,如果您想为后代保留原始答案,只需将其作为“原始答案”或其他内容放在下面。我想我们都同意head 是要走的路,特别是因为render nothing: true 在当前的Rails 版本中已被弃用。
    • @JoshuaPinter:确实。我在想什么?
    【解决方案3】:

    以下对我有用:

    format.any { render :json => {:response => 'Unable to authenticate' },:status => 401  }
    

    HTML 响应的:response 以防万一从浏览器访问它。

    渲染头 503 似乎不适用于上述语句。

    【讨论】:

    • 这对 SEO 不利。例如,Google 会将此视为一个损坏的站点,而不仅仅是一个暂时关闭但预计会恢复的站点。看到这个:yoast.com/http-503-site-maintenance-seo
    • 可能值得将其更改为“服务不可用”/503,因此它与问题的目的相匹配。我认为这是对您不起作用的“渲染头”语法,而不是错误代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    相关资源
    最近更新 更多