1

我从这里使用自定义 JSONP 格式化程序: http ://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

它适用于最新的 Web API。但是,我如何限制它不适用于我的所有 Web API 服务,而只有我放置 JSONP 属性或其他东西的那些。关于如何确保仅针对我选择的某些操作的任何想法?

4

1 回答 1

1

如果您可以按照想要作为 JSONP 返回的对象的类型来考虑,而不是操作,则可以像这样更改格式化程序以仅允许将某些类型序列化为 JSONP。

public override bool CanWriteType(Type type)
{
    // Check type here and return true only for the types you want to allow JSONP
    return true;
}

如果基于类型的过滤是不可能的,另一种选择是不将格式化程序添加到格式化程序集合中,并JsonpFormatter像这样显式指定,仅在您想要返回 JSONP 的操作方法中。

return new HttpResponseMessage()
{
    Content = new ObjectContent<MyType>(anInstanceOfMyType, new JsonpFormatter())
};

然而,一个缺点是这将只返回 JSONP,无论 conneg 出现什么。

于 2013-08-07T02:49:46.823 回答