是否有 ASP.NET 获取 JSON 数据的样板方式?

Is there an ASP.NET Boilerplate Way of getting JSON data?

我目前正在尝试此操作,但我一直看到可怕的错误:

Unexpected token o in JSON at position 1

我正在努力寻找解决方案,想知道是否有人对如何解决这个问题有任何建议?

class被序列化为JSON:

[Serializable]
public class GeoCoordinate
{
    public GeoCoordinate()
    {
    }

    [JsonProperty(PropertyName = "lat")]
    public double Latitude { get; }

    [JsonProperty(PropertyName = "long")]
    public double Longitude { get; }

    public GeoCoordinate(double latitude, double longitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", Latitude, Longitude);
    }
}

Ajax 调用:

function getLocationData() {
    jQuery.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: "GET",
        dataType: "json",
        async: true,
        success: function (data) {
            var myArray = jQuery.parseJSON(data);
            locations = [];
            $.each(myArray, function (index, element) {
                locations.push([element.lat, element.long]);
            });
        }
    });
}

控制器:

[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

应用服务:

public async Task<IList<GeoCoordinate>> GetAllGeoCoordinates()
{
    var geoCoordinates = await Repository.GetAll()
        .Where(x => !x.Disabled && !x.Latitude.Equals(0) && !x.Longitude.Equals(0))
        .Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
        .ToListAsync();

    return geoCoordinates;
}

Console.log 尝试调用 parseJSON 之前的数据:

console.log(data);
var myArray = jQuery.parseJSON(data);

如果 return 类型是 JsonResult,

ASP.NET 样板默认包装 ASP.NET MVC 操作结果。因此,如果您想获得结果,您可以禁用换行。尝试将 [DontWrapResult] 属性添加到 GetLocationsAsync 方法。

[DontWrapResult]
[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

PS: 您不需要添加此属性。您可以从 result 字段中获取。通过浏览器的开发控制台检查响应以查看其包装方式。

巧合的是,有一个名为 The ASP.NET Boilerplate Way 的部分正好解决了这个问题。

请注意,只有第 2 点特定于 ABP:

  1. GetLocationsAsync return是一个 JSON 对象而不是字符串,所以你不应该调用 parseJSON.

    您可以通过以下方式重现错误消息:jQuery.parseJSON({});

  2. ABP 换行 JsonResult。来自 AJAX Return Messages 的文档:

    This return format is recognized and handled by the abp.ajax function.

    您可以使用 [DontWrapResult] 属性,但您也可以在这里利用 ABP。 abp.ajax handles the display of error messages 如果你抛出 UserFriendlyException.

  3. 由于ajax是异步的,getLocationData不能直接returnlocations

    您可以先 return 链接 Promise. If you're new to Promises, read Using Promises

  4. 有比 $.eachpush 更简洁的方法。

    你可以使用map.

最后:

function getLocationData() {
    return abp.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: 'GET'
    }).then(function (result) {
        return result.map(function (element) {
            return [element.lat, element.long];
        });
    });
}

用法:

getLocationData().then(function (locations) {
    console.log(locations);
});