2013-10-16 27 views

回答

4

創建請求過濾器屬性,設置標誌在請求上下文中說跳過認證:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 
public class NoAuthenticateAttribute : RequestFilterAttribute { 

    public NoAuthenticateAttribute() : this(ApplyTo.All) {} 

    public NoAuthenticateAttribute(ApplyTo applyTo) : base(applyTo) { 
     // execute this before any AuthenticateAttribute executes. 
     // https://github.com/ServiceStack/ServiceStack/wiki/Order-of-Operations 
     Priority = this.Priority = ((int) RequestFilterPriority.Authenticate) - 1; 
    } 

    public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) 
    { 
     req.Items["SkipAuthentication"] = true; 
    } 
} 

,創造AuthenticateAttribute自定義子類,檢查該標誌在請求:

public class MyAuthenticateAttribute : AuthenticateAttribute { 
    public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) 
    { 
     if (!ShouldSkipAuthenticationFor(req)) 
      base.Execute(req, res, requestDto); 
    } 

    private bool ShouldSkipAuthenticationFor(IHttpRequest req) 
    { 
     return req.Items.ContainsKey("SkipAuthentication"); 
    } 
} 

用法:

[MyAuthenticate] 
public class MyService : Service 
{ 
    public object Get(DtoThatNeedsAuthentication obj) 
    { 
     // this will be authenticated 
    } 

    [NoAuthenticate] 
    public object Get(DtoThatShouldNotAuthenticate obj) 
    { 
     // this will not be authenticated 
    } 
} 
+0

雖然我投了這個答案,但解決方案並不適合我。它僅調用MyAuthenticate屬性,並且未能調用NoAuthenticate屬性。 – theoutlander

+0

@theoutlander你的意思是不調用NoAuthenticateAttribute類中的Execute方法?你在哪裏應用你的MyAuthenticate和NoAuthenticate屬性? –

+0

是的,這是正確的。 – theoutlander