覆盖 NancyFx 中响应的默认 Content-Type [英] Override the default Content-Type for responses in NancyFx

查看:72
本文介绍了覆盖 NancyFx 中响应的默认 Content-Type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NancyFx 编写 REST API.我经常收到这样的代码:

I'm writing a REST API with NancyFx. I often got code like this:

Post["/something"] = _ => {
// ... some code
if (success) 
    return HttpStatusCode.OK;
else
    return someErrorObject;
};

客户端始终假定 application/json 作为所有响应的内容类型.它实际上在请求中设置了 Accept: application/json.无论实际正文如何,没有 application/json 的响应都是错误.它只是检查内容类型,如果与 json 不匹配则中止.我无法改变这种行为.

The client always assumes application/json as the content type of all responses. It actually sets Accept: application/json in the request. Responses without application/json are errors regardless of the actual body. It simply checks the content type and aborts if it doesn't match json. I can't change this behaviour.

现在我面临的问题是通过简单地返回 HttpStatusCode.OK Nancy 设置 Content-Type: text/html 但正如所说,客户端假设 application/json 并失败即使正文为空也会出错.

Now I face the problem that by simply returning HttpStatusCode.OK Nancy sets Content-Type: text/html but as said the client assumes application/json and fails with an error even the body is empty.

我能够像这样强制内容类型:

I was able to force the content type like this:

return Negotiate
    .WithContentType("application/json")
    .WithStatusCode(HttpStatusCode.OK);

我不想到处重复这段代码.当然,我可以将其抽象为单个函数,但我正在寻找更优雅的解决方案.

I don't want to repeat this code everywhere. Of course I could abstract that in a single function but I'm looking for a more elegant solution.

有没有办法覆盖响应的默认 Content-Type,以便 return HttpStatusCode.OK 将我的 Content-Type 设置为 application/json?

Is there a way to override the default Content-Type of respones so that return HttpStatusCode.OK sets my Content-Type to application/json?

推荐答案

基于想要将所有响应作为 JSON 返回的假设,您将需要一个自定义引导程序.如果您愿意,您可以通过使用插入而不是清除响应处理器来进一步增强这一点,因此可以回退使用 XML 处理器等.

Based on the assumption of wanting to return all responses as JSON you will need a custom bootstrapper. You can enhance this further if you like by using an insert as opposed to clearing the response processors thus the fallback of using the XML processor etc is possible.

这将被 Nancy 自动获取,无需额外配置.

This will get automatically picked up by Nancy by the way no additional configuration required.

public class Bootstrap : DefaultNancyBootstrapper
{
    protected override NancyInternalConfiguration InternalConfiguration
    {
        get
        {
            return NancyInternalConfiguration.WithOverrides(
                (c) =>
                {
                    c.ResponseProcessors.Clear();
                    c.ResponseProcessors.Add(typeof(JsonProcessor));
                });
        }
    }
}

这篇关于覆盖 NancyFx 中响应的默认 Content-Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆