【问题标题】:Grails - content-type dependent afterInterceptorGrails - 依赖于内容类型的 afterInterceptor
【发布时间】:2011-12-22 09:32:09
【问题描述】:

我可以根据内容类型在拦截器后设置控制器吗?

示例:只有传入请求类型为application/json时才调用afterInterceptor;否则不要调用 afterInterceptor

我没有找到方法,并且“withFormat”闭包方法在每个操作上都设置起来很麻烦。

只有当传入的请求类型是 json 时,我才想将模型转换为 json。

或者,还有其他方法可以实现我的目标吗?

提前致谢, 托德

【问题讨论】:

    标签: json grails


    【解决方案1】:

    您可以在 afterInterceptor 中添加一个保护子句,如果请求内容类型不是 JSON,则该子句会退出。

    def afterInterceptor = { model ->
        if (request.getHeader('Content-Type')?.startsWith('application/json')) {
            return
        }
        //do your json stuff here
    }
    

    或者,如果您真的对传入的 Accept 标头感兴趣,那么您可以使用

    if (request.format != 'JSON') return
    

    【讨论】:

    • 我们是否可以访问 afterInterceptor 中的请求?我不这么认为,但会尝试一下。
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 2023-03-21
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    相关资源
    最近更新 更多