【发布时间】:2018-03-07 08:18:07
【问题描述】:
我的目标是在 Grails 3.1 控制器方法中呈现 HTTP 响应,该方法具有
- 一个给定的状态码(主要是
204,但也可能是其他的,比如200) -
没有
Content-Type或Content-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