Using System.Net.IpAddress as complex type in oData model but serializing/deserializing as string
ChesireFreeThrow opened this issue · comments
I have a model that is using System.Net.IpAddress and need the odata web service to serialize/deserialize it as a string and not a comples type. How would I do that? It doesn't know what to do with the IpAddress by default.
public class TestModel
{
public int Id { get; set; }
public IPAddress Ipaddress { get; set; }
}
public class EdmModel
{
public IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
var ip = builder.ComplexType<IPAddress>();
//ip.Ignore(i => i.Address);
ip.Ignore(i => i.AddressFamily);
ip.Ignore(i => i.IsIPv4MappedToIPv6);
ip.Ignore(i => i.IsIPv6LinkLocal);
ip.Ignore(i => i.IsIPv6Multicast);
ip.Ignore(i => i.IsIPv6Teredo);
ip.Ignore(i => i.IsIPv6UniqueLocal);
ip.Ignore(i => i.ScopeId);
var model = builder.EntitySet<TestModel>("TestModel").EntityType;
model.ComplexProperty(p => p.Ipaddress).IsRequired();
return builder.GetEdmModel();
}
}
Duplicate of:
TL;DR it's not trivial, but also not impossible. I've not yet done it myself as the opportunity hasn't come up again (when I asked that question I was in a different company/project where I was looking to add some custom types to our OData service).
Couple ways:
- Extra property mapping
You can define an extra string property as:
public class TestModel
{
public int Id { get; set; }
public string IpAddressStr { get => Ipaddress.ToString(); set => Ipaddress = value.ToIpAddress(); }
public IPAddress Ipaddress { get; set; }
}
When doing model builder, exclude 'Ipaddress' from Edm model, rename 'IpAddressStr' as 'Ipaddress'.
-
Define a customized Edm Type.
You can refer to my sample at:
https://github.com/xuzhg/WebApiSample/tree/main/v8.x/CreateNewTypeSample -
Customize "IODataTypeMapper". (I haven't had sample to test it, if needed, I can try it later)
@xuzhg Thanks!
I was trying to avoid the first one but I'll try the other two out