如何根据返回的错误类型配置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;
});
答案 0 :(得分: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和HttpListener请求的HttpHandler。创建一个的最简单方法是从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");
}