ASP.NET/ EF Core/ NetTopologySuite 使用GeoJSON进行数据传输
以Postgresql为例,首先安装依赖:
dotnet add package NetTopologySuite dotnet add package Npgsql.NetTopologySuite
对于一个Location数据:
[Table("location")] public class Location { public string Name {get;set;} public NetTopologySuite.Geometries.LineString? Geom {get;set;} }
以.net6为例,通过在Program.cs
中添加GlobalTypeMapper
:
NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();
之后需在为自己的DbContext
添加如下配置:
builder.Services.AddDbContext<MyDbContext>(options => options .UseNpgsql("your-db-connection-string", x => x.UseNetTopologySuite()) );
至此,已完成模型>>PostGIS类型的映射,当写好Controller希望测试新增记录的接口的时候,会发现好像没有一个合适的方法来进行数据传输。
我想偷懒,测试了两种比较通用的明文格式GeoJSON和WKT作为描述:
{ "Name":"example", "Geom":{ 'type': 'LineString', 'coordinates': [ [122.483696, 37.833818], [122.492237, 37.833378], [122.493782, 37.833683] ] } } ··· { "Name":"example", "Geom":"LINESTRING (30 10, 10 30, 40 40)" }
得到了一样的结果:
Unable to find a constructor to use for type NetTopologySuite.Geometries.LineString
看来Npgsql/NetTopologySuite没有定义隐式的转换,因此需要声明一个JsonConverter来强制执行这一转换,参考这个问题
https://github.com/NetTopologySuite/NetTopologySuite.IO.GeoJSON/issues/17#issuecomment-441620819
我们首先需要添加NetTopologySuite的GeoJSON拓展
dotnet add package NetTopologySuite.IO.GeoJSON
之后添加为空间字段添加JsonConverter
:
[Table("location")] public class Location { public string Name {get;set;} [Newtonsoft.Json.JsonConverter(typeof(NetTopologySuite.IO.Converters.GeometryConverter))] public NetTopologySuite.Geometries.LineString? Geom {get;set;} }
这样,通过下面的Request Body就可以正确的解析出空间字段了。
{ "Name":"example", "Geom":{ 'type': 'LineString', 'coordinates': [ [122.483696, 37.833818], [122.492237, 37.833378], [122.493782, 37.833683] ] } } [HttpPost("line")] public IActionResult AddLocation([FromBody] Location location) { _myDbContext.Locations.Add(location); _myDbContext.SaveChanges(); return Ok(); }
综上完成了nts-postgis的类型映射,实现了通过GeoJSON的数据传输,但如果使用Swagger UI的话,NTS的Geometry类型的Example Value是一个复杂的结构体,不方便通过Swagger UI调试,至于修改空间字段的Example Value,之后再做补充。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南