2013-11-20 51 views
0

我想創建一個將在某些控制器中調用以檢查身份驗證的anotation。Play Framework 2.2如何設置響應覆蓋呼叫動作的狀態代碼

在老遊戲版本,直到2.1,我用這個下面的代碼播放的首要調用操作:

public class OAuth2Action extends Action<OAuth2> { 

    // ... 
    @Override 
    public Result call(Http.Context context) throws Throwable 
    { 
     if (authorization == null) 
      return unauthorized(ACCESS_TOKEN_NOT_FOUND); 

     return delegate.call(context); 
    } 
} 

它返回的結果,那麼就可以很容易地返回HTTP狀態代碼401未授權的響應就像控制器

在玩2.2調用方法改變,必須返回F.Promise

我寫了這以下,使其工作:

public class OAuth2Action extends Action<OAuth2> { 
    // ... 
    @Override 
    public F.Promise<SimpleResult> call(Http.Context context) throws Throwable {  
     if (authorization == null) {   
      // return unauthorized(ACCESS_TOKEN_NOT_FOUND); // Now i can't use this 
      // I can set Header, Content type, cookies, BUT NOT STATUS CODE 
      context.response().setHeader("Header", "test"); 
     } 

     return delegate.call(context); 
    } 
} 

我希望返回狀態碼401的響應,你能幫我解決這個問題嗎?

回答

2

試試這個:

public class OAuth2Action extends Action<OAuth2> { 
    // ... 
    @Override 
    public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable { 
     if (authorization == null) { 
      return F.Promise.promise(new F.Function0<SimpleResult>() { 
       @Override 
       public SimpleResult apply() throws Throwable { 
        return unauthorized(ACCESS_TOKEN_NOT_FOUND); 
       } 
      }); 
     } 
     return delegate.call(ctx); 
    } 
} 
+1

據我所知,許呼叫可以被減少到'返回F.Promise.pure(未授權(ACCESS_TOKEN_NOT_FOUND));' – knittl

+0

@knittl,是F.Promise對於返回已經計算好的(常量)值,.pure也是正確的和很好的解決方案。 – Serg