NancyFx 每个模块或每个路由序列化

NancyFx per module or per route serialization

我使用 NancyFx,我试图在提问之前找到答案。

我每个模块有一个 return 类型,但是在不同的 URL 路由中我需要以不同的方式序列化它,只是特定的属性。 如果我在 Nancy 管道中连线序列化,它会涉及所有路由。

是否可以自定义每个路由或模块的序列化,而无需在不同的命名空间中复制粘贴相同的类型?

我想出了两个解决方案:

  1. 在相应的覆盖道具上具有 JsonConvert 属性的派生类型;
  2. 在模块内使用序列化和 return string

在没有更好地了解要求的情况下不确定具体推荐什么。

考虑实施响应处理器。

在您的 CanProcess 实现中,您可以检查 NancyContext 来评估您的规则以使用哪种序列化方案。

示例:

public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
    {
        return context.Request.Path != "/" && 
            !context.Request.Path.StartsWith("/someroute/") && 
            !context.Request.Path.StartsWith("/someotherroute") &&
            !context.Request.Path.StartsWith("/login")
            ? new ProcessorMatch
            {
                ModelResult = MatchResult.DontCare,
                RequestedContentTypeResult = MatchResult.ExactMatch
            }
            : new ProcessorMatch
            {
                ModelResult = MatchResult.DontCare,
                RequestedContentTypeResult = MatchResult.NoMatch
            };
    }

https://github.com/NancyFx/Nancy/wiki/Content-Negotiation

考虑:使用 WithMediaRangeModel 作为路由的内容协商。

Enables you to define media type specific models that should be used during negotiation. The negotiation pipeline will first attempt to find a media type specific model to use and will fallback to the default model, which is specified using WithModel, if it fails.