NancyFx:如何将错误消息传递给自定义错误页面?

时间:2017-01-31 02:04:50

标签: c# razor nancy

我们使用Razor和此处记录的IStatusCodeHandler实现为404/500 HTTP状态代码实现了静态自定义错误页面:

https://blog.tommyparnell.com/custom-error-pages-in-nancy/

这有效,现在我们一直试图将错误消息传递给Razor模板。 RenderView方法毫无例外地运行,但输出完全空白。

在Handle方法中,我们构造一个ErrorModel对象并设置其ErrorMessage属性,然后将该对象传递给RenderView:

var response = viewRenderer.RenderView(context, "views/Errors/" + (int)statusCode + ".cshtml", errorModel);

CustomStatusCode.cs代码是:

public class CustomStatusCode : IStatusCodeHandler
{
    private readonly ILog _log = LogManager.GetLogger<CustomStatusCode>();

    private static IEnumerable<int> _checks = new List<int>();
    public static IEnumerable<int> Checks { get { return _checks; } }
    private IViewRenderer viewRenderer;
    public CustomStatusCode(IViewRenderer viewRenderer)
    {
        this.viewRenderer = viewRenderer;
    }

    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
    {
        return (_checks.Any(x => x == (int)statusCode));
    }

    public static void AddCode(int code)
    {
        AddCode(new List<int>() { code });
    }

    public static void AddCode(IEnumerable<int> code)
    {
        _checks = _checks.Union(code);
    }

    public static void RemoveCode(int code)
    {
        RemoveCode(new List<int>() { code });
    }

    public static void RemoveCode(IEnumerable<int> code)
    {
        _checks = _checks.Except(code);
    }

    public static void Disable()
    {
        _checks = new List<int>();
    }

    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        var errorMessage = string.Empty;
        var exception = context.GetException();
        if (exception != null)
        {
            errorMessage = exception.Message;
        }
        var errorModel = new ErrorModel(errorMessage);

        try
        {
            var response = viewRenderer.RenderView(context, "views/Errors/" + (int)statusCode + ".cshtml", errorModel);

            response.StatusCode = HttpStatusCode.OK;
            context.Response = response;
        }
        catch (Exception ex)
        {
            _log.Debug($"CustomStatusCodes caught exception: {ex.Message}");

            RemoveCode((int)statusCode);
            context.Response.StatusCode = statusCode;
        }
    }

}

ErrorModel.cs类是:

public class ErrorModel
{
    public ErrorModel(string message)
    {
        ErrorMessage = message;
    }

    string ErrorMessage { get; set; }
}

其中一个Razor模板:

@using WebService.Models
@Model ErrorModel

<html>
<body>
    <b>500 Internal server error.</b>
    <p>Error message was: @Model.ErrorMessage</p>
</body>
</html>

我们尝试过设置response.StatusCode到原来的statusCode参数值,以及HttpStatusCode.OK,都会产生一个空白页面。

有关我们遗失的内容的任何建议吗?

0 个答案:

没有答案