简体   繁体   中英

Grails - content-type dependent afterInterceptor

Can I set a controller afterInterceptor based on content-type?

Example: only call afterInterceptor if the incoming request type is application/json; otherwise do not call afterInterceptor

I'm not finding a way and the "withFormat" closure approach is going to be cumbersome to set on every action.

I want to convert the model to json only if the incoming request type is json.

Or, are there other ways to achieve my goal?

Thanks in advance, Todd

You can add a guard clause to your afterInterceptor that exits if the request content-type is not JSON.

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

Or, if you are really interested in the incoming Accept header, then you would use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM