我正在使用新的ASP.NET webapi odata(版本4.0.0,根据Nuget上次发布于2013年2月27日)
基本上我按照这里描述的那样做:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api
我正在发布我的数据传输对象,并创建了odata atom pub Feed,但我想对它有更多的控制权.主要是我希望能够做到以下几点:
>确定Feed的标题,作者和更新元素的内容
>决定是否拥有编辑链接
>更改< category term =“X”和m中显示的内容:键入我的应用程序中的类的子属性.目前,他们使用完整的命名空间公开c#类名,但我不想公开它.
谢谢.
解决方法
OData媒体类型格式化器现在更具扩展性.样品如下.
public class AtomMetadataFeedSerializer : ODataFeedSerializer { public AtomMetadataFeedSerializer(IEdmCollectionTypeReference edmType,ODataSerializerProvider serializerProvider) : base(edmType,serializerProvider) { } public override ODataFeed CreateODataFeed(IEnumerable FeedInstance,ODataSerializerContext writeContext) { ODataFeed Feed = base.CreateODataFeed(FeedInstance,writeContext); Feed.Atom().Title = new AtomTextConstruct { Kind = AtomTextConstructKind.Text,Text = "My Awesome Feed" }; return Feed; } } public class CustomSerializerProvider : DefaultODataSerializerProvider { public override ODataEntrySerializer CreateEdmTypeSerializer(IEdmTypeReference edmType) { if (edmType.IsCollection() && edmType.AsCollection().ElementType().IsEntity()) { // Feed serializer return new AtomMetadataFeedSerializer(edmType.AsCollection(),this); } return base.CreateEdmTypeSerializer(edmType); } }
config.Formatters.InsertRange(0,ODataMediaTypeFormatters.Create(new CustomSerializerProvider(),new DefaultODataDeserializerProvider()));
public class CustomEntityTypeSerializer : ODataEntityTypeSerializer { public CustomEntityTypeSerializer(IEdmEntityTypeReference edmType,serializerProvider) { } public override ODataEntry CreateEntry(EntityInstanceContext entityInstanceContext,ODataSerializerContext writeContext) { ODataEntry entry = base.CreateEntry(entityInstanceContext,writeContext); if (notProduceEditLinks) { entry.EditLink = null; } return entry; } } public class CustomSerializerProvider : DefaultODataSerializerProvider { public override ODataEntrySerializer CreateEdmTypeSerializer(IEdmTypeReference edmType) { if (edmType.IsEntity()) { // entity type serializer return new CustomEntityTypeSerializer(edmType.AsEntity(),this); } return base.CreateEdmTypeSerializer(edmType); } }