【问题标题】:render an empty HTTP response with Grails 3使用 Grails 3 呈现一个空的 HTTP 响应
【发布时间】:2018-03-07 08:18:07
【问题描述】:

我的目标是在 Grails 3.1 控制器方法中呈现 HTTP 响应,该方法具有

  • 一个给定的状态码(主要是204,但也可能是其他的,比如200
  • 没有Content-TypeContent-Encoding 标题(因为没有内容,对吧?)

render(status: 204) 添加任意Content-Type: application/json 标头。

此外,这个方法(见grails.artefact.controller.support.ResponseRenderer.render())在这种情况下调用HttpServletResponse.sendError(),虽然它不是错误。这是为什么呢?

目前我们通过直接处理response来解决这个问题:

response.status = statusCode.value()
response.flushBuffer()

但这会阻止我们使用 Grails 拦截器 after 方法在发送响应之前执行某些操作。这就是为什么我们正在寻找一种不同的方式,它不会改变 HTTP 响应(比如添加一个Content-Type 标头)。

【问题讨论】:

  • 你不能将contentType: 'whatever/you-want' 传递给render() 以及status 吗?
  • render 方法忽略 contentType 属性,如果没有传递任何正文(例如通过 text 属性)。
  • 我知道这是旧的,但对于任何有关于“渲染方法忽略 contentType 属性”的问题的人来说,诀窍是在传入的参数中添加一个空的 text: ''渲染方法。示例:render(contentType: "application/json", text: '', status: HttpStatus.ACCEPTED)。这样会考虑到 contetType。

标签: grails groovy grails-3.1


【解决方案1】:

你可以这样写:

response.status = 204
render ""

这将以 text/html;charset=utf-8 的形式返回 Content-Type 标头。要更改内容类型,您可以使用 Grails 中的内容协商。

要完全删除Content-Type 标头,您可以尝试response.setHeader("Content-Type", "")

【讨论】:

  • 这会添加 Content-Type: text/html;charset=utf-8 标头。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2015-04-17
  • 2021-02-25
  • 2018-09-01
相关资源
最近更新 更多