[英]play 2.3.x framework: How to decline all non application/json requests
In play 2.3, how can I automatically reject (return BadRequest) all incoming requests that are not of type application/json? 在播放2.3中,如何自动拒绝(返回BadRequest)所有非application / json类型的传入请求? Is there an annotation type like for BodyParsers? 是否有类似于BodyParsers的注释类型?
I don't want to add an extra check: 我不想添加额外的支票:
@BodyParser.Of(BodyParser.Json.class)
public static Result sendMessage() {
JsonNode requestBody = request().body().asJson();
if (requestBody == null) {
return badRequest("Bad Request: Not JSON request");
}
return ok();
}
Probably the most flexible way is creating own interceptor - aka Action composition 也许最灵活的方法是创建自己的拦截器-aka Action composition
Sample RequiredJson.java
(let's place it in new annotations
package) 样本RequiredJson.java
(将其放置在新的annotations
包中)
package annotations;
import com.fasterxml.jackson.databind.JsonNode;
import play.libs.F;
import play.mvc.Http;
import play.mvc.Result;
public class RequiredJson extends play.mvc.Action.Simple {
@Override
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
boolean hasCorrectType = ctx.request().getHeader("Content-Type") != null && ctx.request().getHeader("Content-Type").equals("application/json");
JsonNode json = ctx.request().body().asJson();
if (!hasCorrectType || json == null) {
return F.Promise.<Result>pure(badRequest("I want JSON!"));
}
return delegate.call(ctx);
}
}
So you can use this annotation for whole controller(s) or for selected action(s) only like: 因此,您只能将此注释用于整个控制器或选定的动作,例如:
@With(annotations.RequiredJson.class)
Result: if Content-Type
isn't valid or if incoming data isn't valid JSON it returns badRequest, otherwise it calls the requested action as usually. 结果:如果Content-Type
无效或传入数据无效JSON,则返回badRequest,否则通常调用请求的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.