【问题标题】:How to secure JSONP requests with Web API?如何使用 Web API 保护 JSONP 请求?
【发布时间】:2013-08-08 03:45:21
【问题描述】:
【问题讨论】:
标签:
c#
security
asp.net-web-api
jsonp
【解决方案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 出现什么。