【问题标题】:play framework2: find out if an app is running on http or httpsplay framework2:查看应用是在 http 还是 https 上运行
【发布时间】:2012-12-10 02:02:12
【问题描述】:

我正在尝试确定 play 2(带有 scala)应用程序是否在 http 或 https 上运行

我尝试使用 routes.Application.index.absoluteURL(request),像这样

def chatUri(username: String)(implicit request: RequestHeader): String = {

  val uri = routes.Application.index.absoluteURL(request)

但我收到以下错误:

/home/sas/tmp/websocket-chat/app/controllers/Application.scala:51: overloaded method value absoluteURL with alternatives:
[error]   (secure: Boolean)(implicit request: play.api.mvc.RequestHeader)java.lang.String <and>
[error]   (play.mvc.Http.Request)java.lang.String
[error]  cannot be applied to (play.api.mvc.RequestHeader)
[error]     val rootUri = Uri(routes.Application.index.absoluteURL(request))

我尝试将 RequestHeader 转换为 Request,但出现以下错误

val rootUri = Uri(routes.Application.index.absoluteURL(request.asInstanceOf[Request[Any]]))

(secure: Boolean)(implicit request: play.api.mvc.RequestHeader)java.lang.String <and>
[error]   (play.mvc.Http.Request)java.lang.String
[error]  cannot be applied to (play.api.mvc.Request[Any])
[error]     val rootUri = Uri(routes.Application.index.absoluteURL(request.asInstanceOf[Request[Any]]))

知道如何实现吗?

【问题讨论】:

    标签: url playframework-2.0 router


    【解决方案1】:

    必须说我对在 Scala 中获取绝对 url 的问题感到惊讶,在 Java 中它运行良好,无论如何...我怀疑它是否会帮助您确定协议(edit:正如@MariusSoutier 所写)

    由于 Play 2 中有 no built-in support for SSL,您很可能正在(或应该使用)您的应用程序前面的一些 HTTP 服务器,比如说 Apache。有一些描述过程的示例和帖子:

    1. 看一下主题:How to config PlayFramework2 to support SSL?Nasir 提供了一个将 Apache 配置为 Play 代理的示例
    2. configuring Apache as a proxy 也有很好的描述(警告 帖子描述的是 Play 1.x,但 Apache 部分将是相同的)
    3. 最后你需要为你的应用设置proper headers which will be forwarded

    所以在设置标题后(如第 3 点所示),您将能够在控制器中检查它:

    def index = Action { request =>
        val proto = request.headers("X-FORWARDED-PROTO")
        Ok("Got request [" + request + "] with schema: " + proto )
    }
    

    或在 Java 控制器中相同:

    public static Result index() {
        String proto = request().getHeader("X-FORWARDED-PROTO");
        return ok("Got request [" + request() + "] with schema: " + proto);
    }
    

    【讨论】:

      【解决方案2】:

      首先,通过创建绝对 URL,您无法确定应用程序是在 http 还是 https 上运行 - 查看方法签名:

      def absoluteURL (secure: Boolean = false)(implicit request: RequestHeader): String
      

      没错,你必须告诉这个方法你是否想要安全。

      我认为这是因为 Play 被设计为在反向代理后面工作,这使得使用加密请求变得透明。这意味着 Play 不必关心这一点。 absoluteURL 只能强制使用 https URL,例如确保登录页面使用 https。

      根据您的反向代理,您可以设置一个自定义的 http 标头,告诉您使用什么。 RequestHeader 没有信息。

      【讨论】:

      猜你喜欢
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2010-11-24
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多