2014-10-05 29 views
0

如何根據返回的錯誤類型將ServiceStack配置爲提供特定的錯誤頁面(404,500等)?服務棧中的自定義錯誤頁面

目前,我使用下面的RawHttpHandler代碼來確保對HTML文件的請求進行身份驗證。但是,如果用戶指定了一個不存在的文件或端點,我如何才能返回我的404.html頁面。

this.RawHttpHandlers.Add(httpReq => 
      { 
       var session = httpReq.GetSession(); 

       if(!session.IsAuthenticated) { 
        var isHtmlFileRequest = httpReq.PathInfo.EndsWith(".html"); 

        if(isHtmlFileRequest && !files.Any(s => httpReq.PathInfo.ToLower().Contains(s))) { 
         return new RedirectHttpHandler { 
          AbsoluteUrl = "/Login.html" 
         }; 
        } 
       } 

       return null; 
      }); 

回答

2

Error Handling wiki顯示不同的方式在ServiceStack Customize Handling of Exceptions,例如,你可以重定向404錯誤/404.cshtml有:

public override void Configure(Container container) 
{ 
    this.CustomHttpHandlers[HttpStatusCode.NotFound] = 
     new RazorHandler("/404"); 
} 

CustomHttpHandlers可以是任何IServiceStackHandler這僅僅是支持ASP.NET中的HttpHandler和HttpListener請求。最簡單的方法是從IServiceStackHandler繼承。下面是類似StaticFileHandler自定義靜態文件處理程序的例子,除了它只是寫出指定filePath而不是使用HTTP請求路徑:

public class CustomStaticFileHandler : HttpAsyncTaskHandler 
{ 
    string filePath; 
    public CustomStaticFileHandler(string filePath) 
    { 
     this.filePath = filePath; 
    } 

    public override void ProcessRequest(HttpContextBase context) 
    { 
     var httpReq = context.ToRequest(GetType().GetOperationName()); 
     ProcessRequest(httpReq, httpReq.Response, httpReq.OperationName); 
    } 

    public override void ProcessRequest(IRequest request, IResponse response, 
     string operationName) 
    { 
     response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r => 
     { 
      var file = HostContext.VirtualPathProvider.GetFile(filePath); 
      if (file == null) 
       throw new HttpException(404, "Not Found"); 

      r.SetContentLength(file.Length); 
      var outputStream = r.OutputStream; 
      using (var fs = file.OpenRead()) 
      { 
       fs.CopyTo(outputStream, BufferSize); 
       outputStream.Flush(); 
      }    
     } 
    } 
} 

這可以被註冊爲標準,即:

public override void Configure(Container container) 
{ 
    this.CustomHttpHandlers[HttpStatusCode.NotFound] = 
     new CustomStaticFileHandler("/404.html"); 
} 
+0

謝謝。之前我曾看到過,但不知道如何在沒有剃刀的情況下使其工作。我必須安裝Razor軟件包嗎?我目前沒有使用它。 – theoutlander 2014-10-05 06:38:41

+0

換句話說,是否有一個文件處理程序或我可以用來簡單地提供一個html文件? – theoutlander 2014-10-05 06:54:19

+0

@theoutlander是RazorHandler需要'ServiceStack.Razor' NuGet包。我已經用一個顯示如何提供靜態文件的示例更新了答案。 – mythz 2014-10-05 07:41:58