【问题标题】:Only allow Nancy to return json or Xml and 406 when accept header is html仅允许 Nancy 在接受标头为 html 时返回 json 或 Xml 和 406
【发布时间】:2015-04-02 11:36:11
【问题描述】:

我正在编写一个 Nancy 端点,我想做一些我认为应该非常简单的事情。我想支持以 json 或 xml 格式返回内容,但是当请求 html 或任何其他类型时返回 406 Not supported。我可以很容易地只强制使用 XML 或 JSON,我想我可以这样做,如果(接受是 html)返回 406,但我会假设在内容协商支持中对此有一些支持。

有人能解释一下吗?

【问题讨论】:

    标签: http nancy content-negotiation


    【解决方案1】:

    实现你自己的 IResponseProcessor,Nancy 会捡起它并挂在引擎中。

    public sealed class NoJsonOrXmlProcessor : IResponseProcessor
        {
            public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
            {
                if (requestedMediaRange.Matches("application/json") || requestedMediaRange.Matches("aaplication/xml"))
                {
                    //pass on, so the real processors can handle
                    return new ProcessorMatch{ModelResult = MatchResult.NoMatch, RequestedContentTypeResult = MatchResult.NoMatch};
                }
                return new ProcessorMatch{ModelResult = MatchResult.ExactMatch, RequestedContentTypeResult = MatchResult.ExactMatch};
            }
    
            public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
            {
                return new Response{StatusCode = HttpStatusCode.NotAcceptable};
            }
    
            public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get; private set; }
        }
    

    【讨论】:

    • 您可能需要用您自己的请求处理器集合覆盖NancyInternalConfiguration,以确保这是第一个。
    【解决方案2】:

    我们避免使用ResponseProcessor 的全部原因是请求仍在通过我们的身份验证层、域层等一直运行。我们想要一种方法来尽快终止请求。

    我们最终做的是在我们自己的Boostrapper 中执行检查

    public class Boostrapper : DefaultNancyBootstrapper
    {
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);
    
            pipelines.BeforeRequest += nancyContext =>
            {
                RequestHeaders headers = nancyContext.Request.Headers
                if (!IsAcceptHeadersAllowed(headers.Accept))
                {
                    return new Response() {StatusCode = HttpStatusCode.NotAcceptable};
                }
                return null;
             }
        }
    
        private bool IsAcceptHeadersAllowed(IEnumerable<Tuple<string, decimal>> acceptTypes)
        {
            return acceptTypes.Any(tuple =>
            {
                var accept = new MediaRange(tuple.Item1);
                return accept.Matches("application/json") || accept.Matches("application/xml");
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多