2

考虑 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"}}

但是如果在 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。

4

2 回答 2

1

也许你可以尝试特定的映射,这样 Grails 就不会尝试在参数中搜索动作名称。像这样:

static mappings = {
    "/action/submit"(controller: 'action', action: 'submit', parseRequest: true)
    "/$controller/$action?/$id?"(parseRequest: true)
}

UrlMappings 工作从特定规则到一般规则,因此第一个规则应该优先。

于 2012-11-12T11:28:22.563 回答
1

问题是parseRequest:true,它解析发布的 JSON 并将其值添加到params. 如果 JSON 包含action这将设置params.action,这反过来将影响执行哪个控制器操作。

您可能值得向http://jira.grails.org提交 JIRA 报告,以要求某种机制从 parseRequest 中排除某些参数,或者更改优先级以便在 UrlMappings 时从 URL 中提取的参数覆盖那些在 JSON 中提供,反之亦然。

于 2012-11-12T11:08:30.677 回答