简体   繁体   English

如何在Play 2.1(Scala)中为任何http方法定义默认操作?

[英]How to define a default Action for any http method in Play 2.1 (Scala)?

I'm writing RESTful web services using the Play framework (Scala variant), version 2.1.1. 我正在使用2.1.1版的Play框架(Scala变体)编写RESTful Web服务。

For a given resource, I want to be able to process POST requests, but for any other method I want to return a MethodNotAllowed response. 对于给定的资源,我希望能够处理POST请求,但是对于其他任何方法,我都希望返回MethodNotAllowed响应。

My routes-file attempt (snippet): 我的路由文件尝试(摘要):

# Item-related actions
POST    /item   controllers.ItemController.newItem
GET     /item   controllers.ApplicationController.methodNotAllowed
PUT     /item   controllers.ApplicationController.methodNotAllowed
DELETE  /item   controllers.ApplicationController.methodNotAllowed
HEAD    /item   controllers.ApplicationController.methodNotAllowed
OPTIONS /item   controllers.ApplicationController.methodNotAllowed
PATCH   /item   controllers.ApplicationController.methodNotAllowed

But I get a warning in the Play console: 但是我在Play控制台收到警告:

[warn] /home/bruno/Entwicklung/pServer/conf/routes:8: unreachable code
[warn] PUT    /itemcontrollers.ApplicationController.methodNotAllowed

How come several, distinct routes can render some “unreachable code”? 几条截然不同的路线如何呈现出一些“无法到达的代码”? I understand the reverse-resolution mechanism should be given a clear set of rules in order to operate without ambiguities, but the direct mechanism, which is what I'm interested in right now, should be working out-of-the-box. 我知道应该为反向分辨率机制提供清晰的规则集,以便在不产生歧义的情况下进行操作,但是我现在感兴趣的直接机制应该是开箱即用的。 Or not? 或不?

Since this case, from my point of view, must be rather common when programming REST services, I'm sure I'm missing something important here. 从我的角度来看,由于这种情况在对REST服务进行编程时必须相当普遍,因此我确信这里缺少一些重要的东西。

Should you have any suggestion as to the best way to approach this problem, I'll appreciate it. 如果您对解决此问题的最佳方法有任何建议,我将不胜感激。

You should not try to figure out all possible bad access points to generate error messages. 您不应尝试找出所有可能的错误访问点来生成错误消息。 Instead, you can override the onHandlerNotFound method in the application's Global object. 而是可以覆盖应用程序的Global对象中的onHandlerNotFound方法。

Adapted from Play's official documentation: ScalaGlobal 改编自Play的官方文档: ScalaGlobal

import play.api._
import play.api.mvc._
import play.api.mvc.Results.__

object Global extends GlobalSettings {
  override def onHandlerNotFound(request: RequestHeader): Result = {
    // implement methodNotAllowed controller Action
  }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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