Asp.Net WebApi自定义媒体格式化程序与特定类型不匹配

时间:2012-11-10 17:05:24

标签: c# asp.net-web-api

我正在检查web api的内容协商和自定义格式化程序,并尝试使用通用的自定义格式化程序。使用RazorEngine我正在解析一个剃刀视图,作为来自web api控制器的响应消息返回。

这是我的格式化程序配置

        GlobalConfiguration.Configuration.Formatters.Insert(0, new RazorViewFormatter<DefaultViewModel>("home-json", new MediaTypeHeaderValue("text/json"), new MediaTypeHeaderValue("application/json")));
        GlobalConfiguration.Configuration.Formatters.Add(new RazorViewFormatter<DefaultViewModel>("home", new MediaTypeHeaderValue("text/html")));
        GlobalConfiguration.Configuration.Formatters.Add(new RazorViewFormatter<IEnumerable<CategoryViewModel>>("categories-json", new MediaTypeHeaderValue("text/json"), new MediaTypeHeaderValue("application/json")));
        GlobalConfiguration.Configuration.Formatters.Add(new RazorViewFormatter<IEnumerable<CategoryViewModel>>("categories", new MediaTypeHeaderValue("text/html")));

使用我的默认资源发出请求,返回正确解析的剃刀视图。

GET http://localhost:56071/api/ HTTP/1.1
User-Agent: Fiddler
Accept: text/json
Host: localhost:56071

然而,对我的类别资源发出请求,只返回我的模型的序列化json而不是解析的模板。基本上缺少标记自定义媒体格式化程序。永远不会调用WriteToStreamAsync()

GET http://localhost:56071/api/categories HTTP/1.1
User-Agent: Fiddler
Accept: text/json
Host: localhost:56071

这不是一种可行的方法吗?我确实在CanReadType上得到了一个匹配,我想知道是否多个格式化程序和它们的连接方式被评估最终不能匹配text / json。

任何想法都表示赞赏。感谢。

更新

public override bool CanWriteType(Type type)
{
    return (type == typeof (T) || type.IsSubclassOf(typeof (T)));
}

public override bool CanReadType(Type type)
{
    return false;
}

0 个答案:

没有答案
相关问题