ServiceStack Razor身份validation

我正在查看Rockstars示例和ServiceStack.Razor。

我如何将身份validation纳入secure.cshtml页面。 因此,如果需要,我可以将用户重定向到Login.cshtml。

我只从SocialBootstrapApi例子中了解如果我混合使用MVC hybird,我可以将[authenticate()]放在ServiceStackController上来实现。

但是,如果我只想要一个没有.net MVC的纯SS项目呢?

Authenticate属性只是一个简单的ServiceStack 请求filter属性 ,即它在MVC和ServiceStack中都有效。

应用此filter将为所有非HTML请求返回401 UnAuthorized响应。 例如,如果您使用Ajax调用此方法,则可以检测到此错误响应并在客户端上执行重定向。

从ServiceStack的v3.9.23 +开始,默认情况下, [Authenticate]属性会自动将所有身份validation错误重定向到~/login url。

您可以在注册AuthFeature时覆盖此URL,例如:

 Plugins.Add(new AuthFeature(...) { HtmlRedirect = "/path/to/my/login" }); 

这将全局应用于所有[Authenticate]属性,或者您可以在adhoc基础上覆盖此属性:

 [Authenticate(HtmlRedirect="/path/to/my/login")] 

注意:属性是可inheritance的,因此您可以将此属性添加到SecuredService类,并且所有子类都将inheritance其行为。

手动重定向

要手动重定向UnAuthorized HTML请求,您可以使用以下命令执行自己的检查+重定向:

 public object Secured(Request request) { if (!base.SessionAs().IsAuthenticated) return new HttpResult(HttpStatusCode.Redirect, "Un Authorized") { Headers = { {"Location", "/path/to/login" } } }; } 

上面的重定向还有一个DRY包装器,您可以使用它:

 public object Secured(Request request) { if (!base.SessionAs().IsAuthenticated) return HttpResult.Redirect("/path/to/login"); }