考虑 Grails 2.1.1 中的以下操作
class ActionController {
static allowedMethods = [submit: 'POST']
def submit() {
render([ok: true, data: request.JSON] as JSON)
}
}
以下命令:
curl -X POST http://localhost:8080/backoffice/action/submit \
-H 'Content-Type: application/json' \
-d '{"foo":"bar"}'
返回
{"ok" : true, "data" : {"foo" : "bar"}}
BUT 如果在 json 中有一个名为 action
的元素,那么 Grails 将尝试查找名称等于该元素值的操作!
例如:
curl -X POST http://localhost:8080/backoffice/action/submit \
-H 'Content-Type: application/json' \
-d '{"foo":"bar","action":"bar"}'
导致 404 错误,因为 grails 正在尝试查找 uri /action/bar.dispatch
!
如何禁用这个奇怪的功能?
我的UrlMappings.groovy
:
static mappings = {
"/$controller/$action?/$id?"(parseRequest: true){
constraints {
// apply constraints here
}
}
该行为是由于 parseRequest=true
引起的吗?我使用此参数是为了能够使用 json 中的 CommandObject。
最佳答案
问题是 parseRequest:true
,它解析发布的 JSON 并将其值添加到 params
中。如果 JSON 包含 action
,这将设置 params.action
,这反过来又会影响执行哪个 Controller 操作。
您可能值得向 http://jira.grails.org 提交 JIRA 报告请求某种机制从 parseRequest 中排除某些参数,或者更改优先级,以便在 UrlMappings 时从 URL 中提取的参数覆盖 JSON 中提供的参数,而不是反之亦然。
关于Grails 解释 json 来查找操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342351/