首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON :如何获得使用ASP.NET会话获得的JSON响应?

JSON :如何获得使用ASP.NET会话获得的JSON响应?
EN

Stack Overflow用户
提问于 2015-01-08 08:42:37
回答 2查看 1.5K关注 0票数 1

我是ASP.NET的新手,但我必须迅速而有力地处理(我知道我在问天空,但我必须这样做)。我有一个页面,它使用谷歌地图显示许多标记。因此,我想异步地向服务器询问坐标。我认为最好的方法是要求他们通过AJAX进行json序列化,并通过ASP会话跟踪地图中已经发送给客户端的部分,并且只发送这些新的部分。我尝试了很多种方式,但我总是发现一些问题打破了魔法。

我的JS代码是:

代码语言:javascript
复制
function map2Json() {
    return JSON.stringify({ "categories": $("#typeSelector input:checked").map(function () {
                                        return $(this).val();
                                    }).get(),
                            "bounds": boundsDecorator(map.getBounds())
                        })
};
function getMarkers() {
    $.ajax({
        type: "POST",
        url: "GetMarkers",
        data: map2Json(),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: OnFailure
    });
}

而我的ASP.NET C#代码(WebService.cs)是:

代码语言:javascript
复制
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMarkers(List<string> categories, Bounds bounds)
{
    System.Diagnostics.Debug.WriteLine(categories.ToString());
    System.Diagnostics.Debug.WriteLine(bounds.SouthWest.lat);

    return JsonConvert.SerializeObject(getMarkers(categories, bounds));
}

private string getRectangle(Bounds bounds)
{
    return string.Format("polygon(({0} {1}, {2} {1}, {2} {3}, {0} {3}, {0} {1}))", bounds.NorthEast.lng.ToString(CultureInfo.InvariantCulture), bounds.NorthEast.lat.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lng.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lat.ToString(CultureInfo.InvariantCulture));
}
private string STpolygon(string polygon)
{
    return string.Format("geography :: STGeomFromText('{0}', 4326)", polygon);
}
private string typologiesListString(List<string> typologies)
{
    return string.Format("({0})", string.Join(",", typologies));
}
private string formatMapNew(List<MapViewed> maps)
{
    return string.Join(" OR ", maps.Select(x => string.Format("{0}.STIntersects(GeoLocation) = 1 and Tipologia = {1}", x.lastPatch.ToString(), x.typology)));
}
private DataSet getCoordinatesInPolygon(List<MapViewed> maps)
{
    SqlCommand Command_coord = new SqlCommand();
    Command_coord.CommandType = CommandType.Text;
    SqlConnection conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=geotagging;Trusted_Connection=Yes;Integrated Security=SSPI;");
    Command_coord.Connection = conn;

    string query = string.Format(@"
                select [Ragione sociale], GeoLocation, Tipologia, Dettagli
                from GEOTAG
                where {0}", formatMapNew(maps));

    Command_coord.CommandText = query;


    DataSet coordinatesDS = new DataSet();
    SqlDataAdapter coordinatesDA = new SqlDataAdapter();
    coordinatesDA.SelectCommand = Command_coord;
    try
    {
        coordinatesDA.Fill(coordinatesDS);
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        System.Diagnostics.Debug.WriteLine("Error query: \n{0}\n Message = {1}", query, e.Message);
    }
    return coordinatesDS;
}
private bool IsEmpty(DataSet dataSet)
{
    foreach (DataTable table in dataSet.Tables)
        if (table.Rows.Count != 0) return false;

    return true;
}
private List<Marker> getDBMarkers(DataSet coordinatesDS)
{
    List<Marker> markers = new List<Marker>();
    SqlGeography point;
    Marker marker;

    if (!IsEmpty(coordinatesDS))
    {
        foreach (DataRow row in coordinatesDS.Tables[0].Rows)
        {
            point = (SqlGeography)row[1];
            marker = new Marker((string)row[0], new Point(point.Lat.Value, point.Long.Value), (string)row[2], (string)row[3]);
            markers.Add(marker);
        }
    }
    return markers;
}
private List<Marker> getMarkers(List<string> typologies, Bounds bounds)
{
    return getDBMarkers(getCoordinatesInPolygon(updatedMaps(bounds, typologies)));
}

private List<MapViewed> updatedMaps(Bounds bounds, List<string> typologies)
{
    List<MapViewed> maps = new List<MapViewed>();
    MapViewed map;
    foreach (string typology in typologies)
    {
        if (Session["mapViewed-" + typology] == null) Session["mapViewed-" + typology] = new MapViewed(typology);
        map = (MapViewed)Session["mapViewed-" + typology];
        map.mergeAndGetDiff(getRectangle(bounds));
        maps.Add(map);
    }
    return maps;
}

请不要过于关注我代码的丑陋之处。我还尝试在页面后面的代码中使用几乎相同的代码,但是我使用的每个方法都应该是静态的,所以我不能使用会话变量。

问题

你怎么做?

备注

我没有将代码插入到地图上,因为没有必要。

解决方案

谢谢大家的建议。按照您的建议,我把这段代码放在后面的代码中,它运行得很好:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using Microsoft.SqlServer.Types;
using System.Data.SqlTypes;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    static SqlConnection conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=geotagging;Trusted_Connection=Yes;Integrated Security=SSPI;");

    protected void Page_Load(object sender, EventArgs e)
    {
        string[] typologies = new string[] { "Ricambi", "Concessionario", "Motocicli", "Officina" };
        foreach (string typology in typologies)
        {
            HttpContext.Current.Session["mapViewed-"+typology] = new MapViewed(typology);
        }
    }
    private static string getRectangle(Bounds bounds)
    {
        return string.Format("polygon(({0} {1}, {2} {1}, {2} {3}, {0} {3}, {0} {1}))", bounds.NorthEast.lng.ToString(CultureInfo.InvariantCulture), bounds.NorthEast.lat.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lng.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lat.ToString(CultureInfo.InvariantCulture));
    }
    private static string STpolygon(string polygon)
    {
        return string.Format("geography :: STGeomFromText('{0}', 4326)", polygon);
    }
    private string typologiesListString(List<string> typologies)
    {
        return string.Format("({0})", string.Join(",", typologies));
    }
    private static string formatMapNew(List<MapViewed> maps)
    {
        return string.Join(" OR ", maps.Select(x => string.Format("{0}.STIntersects(GeoLocation) = 1 and Tipologia = '{1}'", STpolygon(x.lastPatch.ToString()), x.typology)));
    }
    private static DataSet getCoordinatesInPolygon(List<MapViewed> maps)
    {
        SqlCommand Command_coord = new SqlCommand();
        Command_coord.CommandType = CommandType.Text;
        Command_coord.Connection = conn;
        string query = string.Format(@"
                        select [Ragione sociale], GeoLocation, Tipologia, Dettagli
                        from GEOTAG
                        where {0}", formatMapNew(maps));
        Command_coord.CommandText = query;
        DataSet coordinatesDS = new DataSet();
        SqlDataAdapter coordinatesDA = new SqlDataAdapter();
        coordinatesDA.SelectCommand = Command_coord;
        try
        {
            coordinatesDA.Fill(coordinatesDS);
        }
        catch (System.Data.SqlClient.SqlException e)
        {
            System.Diagnostics.Debug.WriteLine("Error query: \n{0}\n Message = {1}", query, e.Message);
        }
        return coordinatesDS;
    }
    private static bool IsEmpty(DataSet dataSet)
    {
        foreach (DataTable table in dataSet.Tables)
            if (table.Rows.Count != 0) return false;
        return true;
    }
    private static List<Marker> getDBMarkers(DataSet coordinatesDS)
    {
        List<Marker> markers = new List<Marker>();
        SqlGeography point;
        Marker marker;

        if (!IsEmpty(coordinatesDS))
        {
            foreach (DataRow row in coordinatesDS.Tables[0].Rows)
            {
                point = (SqlGeography)row[1];
                marker = new Marker((string)row[0], new Point(point.Lat.Value, point.Long.Value), (string)row[2], (string)row[3]);
                markers.Add(marker);
            }
        }
        return markers;
    }
    private static List<Marker> getMarkers(List<string> typologies, Bounds bounds)
    {
        return getDBMarkers(getCoordinatesInPolygon(updatedMaps(bounds, typologies)));
    }

    private static List<MapViewed> updatedMaps(Bounds bounds, List<string> typologies)
    {
        List<MapViewed> maps = new List<MapViewed>();
        MapViewed map;
        foreach (string typology in typologies)
        {
            map = (MapViewed)HttpContext.Current.Session["mapViewed-" + typology];
            map.mergeAndGetDiff(getRectangle(bounds));
            maps.Add(map);
        }
        return maps;
    }

    [System.Web.Services.WebMethod(EnableSession = true)]
    public static List<Marker> GetMarkers(List<string> categories, Bounds bounds)
    {
        return getMarkers(categories, bounds);
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-08 08:48:30

您可以在这样的静态方法中使用会话

代码语言:javascript
复制
//Store value in session
HttpContext.Current.Session["mysession"]=value;

//Get value from session
var sessionvaue=HttpContext.Current.Session["mysession"];
票数 1
EN

Stack Overflow用户

发布于 2015-01-08 08:48:05

使用静态HttpContext.Current性质访问会话变量:

代码语言:javascript
复制
HttpContext.Current.Session
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27835988

复制
相关文章

相似问题

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