首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Web忽略DbGeography的自定义DbGeography

Web忽略DbGeography的自定义DbGeography
EN

Stack Overflow用户
提问于 2016-05-23 17:35:26
回答 1查看 827关注 0票数 4

与此斗争的主要人物。因此,我试图将嵌套的Json数据发送到我的web中。我有一个为我的DbGeography类型定制的子转换器。但是,当我发送请求时,似乎从未调用过我的自定义转换器。我收到错误的说法:无法将对象类型对象强制转换为DbGeography。我使用数据库优先EF作为我的数据模型。注释掉locationAccountCreated属性,其他一切都可以正常工作,数据将成功地保存到数据库中。

如能提供任何帮助,将不胜感激。

请参阅下面的代码

控制器

代码语言:javascript
复制
[Route("Create")]
[HttpPost]
public HttpResponseMessage PostNewAccount([FromBody]IDictionary<string, object> formData) 
{
    if (formData != null)
    {
        var nValueCol = formData;

        var account = new Account()
        { 
            Email = (string)nValueCol["email"],
            Password = (string)nValueCol["password"],
            AgreedToTerms = Convert.ToBoolean(nValueCol["agreesToTerms"]),
            LocationAccountCreated = (DbGeography)nValueCol["userLocation"]//source of error
            //LocationAccountCreated = (DbGeography)(IDictionary<string, IDictionary<string, double>>)nValueCol["userLocation"] 
        };

       //...rest of code unrelated to problem
}

自定义凸点

代码语言:javascript
复制
public class DbGeographyConverter : JsonConverter
{
    private const string LATITUDE_KEY = "latitude";
    private const string LONGITUDE_KEY = "longitude";
    public override bool CanConvert(Type objectType)
    {
        return objectType.Equals(typeof(DbGeography));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if(reader.TokenType == JsonToken.Null) // checks if token is null.
        {
            return default(DbGeography);
        }

        var jObject = JObject.Load(reader);

        if (!jObject.HasValues || (jObject.Property(LATITUDE_KEY)) == null || (jObject.Property(LONGITUDE_KEY)) == null) //checks if Json Object is null, and if longitude or latitude properties are null
        {
            return default(DbGeography);
        }

        string wellKnownText = string.Format("POINT({0} {1})", jObject[LATITUDE_KEY], jObject[LONGITUDE_KEY]);
        return DbGeography.FromText(wellKnownText, DbGeography.DefaultCoordinateSystemId);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dbGeography = value as DbGeography;

        serializer.Serialize(writer, dbGeography == null || dbGeography.IsEmpty ? null : new { latitude = dbGeography.Latitude.Value, longitude = dbGeography.Longitude.Value });
    }
}


public class QueryLocationMetadata
{
    [JsonConverter(typeof(DbGeographyConverter))]
    public virtual System.Data.Entity.Spatial.DbGeography LocationAccountCreated { get; set; }
}

部分类

代码语言:javascript
复制
[MetadataType(typeof(QueryLocationMetadata))]
public partial class Account
{        
}

Global.asax

代码语言:javascript
复制
protected void Application_Start()
{
    var config = GlobalConfiguration.Configuration;

    //Registering routes from the WebApi.Config file
    GlobalConfiguration.Configure(Config.WebApiConfig.Register);


    //Registering Autofac
    GlobalConfiguration.Configure(Config.AutofacConfig.Initialize);

//Registering Formatter
    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DbGeographyConverter());
}

Fiddler请求

代码语言:javascript
复制
http://localhost:9576/Account/Create

User-Agent: Fiddler
Content-type: application/json
Host: localhost:9576
Content-Length: 316


{
  "email":"e02f6rt7fgvujtgv@myuct.ac.za",
  "firstName":"myFName",
  "lastName":"myFName",
  "dateOfBirth":"1992-02-18",
  "password":"password",
  "agreesToTerms":true,
  "userName" : "Cool User",
  "gender" : "Female",
  "userLocation": {"geopoint":{"latitude" : 40.334910, "longitude" :  -32.254586}}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-23 18:30:14

尝试将其作为第一个提供程序插入:

代码语言:javascript
复制
config.Formatters.JsonFormatter.SerializerSettings.Converters.Insert(0, new DbGeographyConverter());

我在Web 2控制器中使用如下的转换器代码尝试了这种方法:

代码语言:javascript
复制
public void Post([FromBody]System.Data.Entity.Spatial.DbGeography value)

也要处理数字格式问题。WKT部分可能需要如下所示:

代码语言:javascript
复制
string wellKnownText = string.Format("POINT({0} {1})", jObject[LATITUDE_KEY].Value<double>().ToString(System.Globalization.NumberFormatInfo.InvariantInfo), jObject[LONGITUDE_KEY].Value<double>().ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37397204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档