ASMX похоже кеширует - PullRequest
       1

ASMX похоже кеширует

2 голосов
/ 13 апреля 2011

У меня есть следующий веб-сервис ASMX:

// removed for brevity //

namespace AtomicService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Assets : WebService
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Validation));
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CityCreate(string cityname, string state, string country,
            decimal timezoneoffset, decimal lat, decimal lon)
        {
            var response = new Dictionary<string, string>();
            if(string.IsNullOrEmpty(cityname) || (string.IsNullOrEmpty(country)))
            {
                response.Add("Response", "empty");
                return JsonConvert.SerializeObject(response, Formatting.Indented);
            }
            int tzid;
            int ctyid;
            try
            {
                tzid = AtomicCore.TimezoneObject.GetTimezoneIdByGMTOffset(timezoneoffset);
                var cty = AtomicCore.CountryObject.GetCountry(country);
                ctyid = cty.CountryId;
            }
            catch (Exception)
            {
                response.Add("Response", "errordb");
                return JsonConvert.SerializeObject(response, Formatting.Indented);
            }
            if(AtomicCore.Validation.DoesCityAlreadyExistByLatLon(cityname, country, lat, lon))
            {
                response.Add("Response", "exists");
                return JsonConvert.SerializeObject(response, Formatting.Indented);
            }
            const string pattern = @"^(?<lat>(-?(90|(\d|[1-8]\d)(\.\d{1,6}){0,1})))\,{1}(?<long>(-?(180|(\d|\d\d|1[0-7]\d)(\.\d{1,6}){0,1})))$";
            var check = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
            bool valid = check.IsMatch(lat + "," + lon);
            if(valid == false)
            {
                response.Add("Response", "badlatlon");
                return JsonConvert.SerializeObject(response, Formatting.Indented);
            }
            BasicConfigurator.Configure();
            Log.Info("User created city; name:" + cityname + ", state:" + state + ", countryid:" + ctyid + ", timezoneid:" + tzid + ", lat:" + lat + ", lon:" + lon + "");

            //will return id of created city or 0.
            var result = AtomicCore.CityObject.CreateCity(cityname, state, ctyid, tzid, lat.ToString(), lon.ToString(), string.Empty);
            response.Add("Response", result > 0 ? "True" : "errordb");
            return JsonConvert.SerializeObject(response, Formatting.Indented);
        }
    }
}

Это вызывается вызовом JQuery $.ajax:

$.ajax({
                            type: "POST",
                            url: "http://<%=Atomic.UI.Helpers.CurrentServer()%>/AtomicService/Assets.asmx/CityCreate",
                            data: "{'cityname':'" + $('#<%=litCity.ClientID%>').val() + "','state':'" + $('#<%=litState.ClientID%>').val() + "','country':'<%=Session["BusinessCountry"]%>','timezoneoffset':'" + $('#<%=litTimezone.ClientID%>').val() + "','lat':'" + $('#<%=litLat.ClientID%>').val() + "','lon':'" + $('#<%=litLng.ClientID%>').val() + "'}",
                            contentType: "application/json",
                            dataType: "json",
                            success: function (msg) {
                                if (msg["d"].length > 0) {
                                    var data = $.parseJSON(msg.d);
                                    if (data.Response > 0) {
                                        //everything has been saved, ideally we
                                        //want to get the cityid and pass it back
                                        //to the map page so we can select it...
                                        alert('Hazzah!');
                                        $(this).dialog('close');
                                    } else {
                                        if(data.Response == 'errordb')
                                        {
                                            alert("db");
                                        }
                                        if(data.Response == 'exists')
                                        {
                                            alert("exists");
                                        }
                                        if(data.Response == 'badlatlon')
                                        {
                                            alert("badlatlon");
                                        }
                                        if(data.Response == 'empty')
                                        {
                                            alert("empty");
                                        }

                                        $('#serviceloader').hide();
                                        $('#<%=txtFindMyCity.ClientID%>:input').attr('disabled', false);
                                        $('#erroroccured').show('slow');
                                        $('#errortext').html("Unfortunately, we can't save this right now. We think this city may already exist within Atomic. Could you please check carefully and try again? If this is an obvious error, please contact us and we'll get you started.");
                                    }
                                } else {
                                    $('#serviceloader').hide();
                                    $('#<%=txtFindMyCity.ClientID%>:input').attr('disabled', false);
                                    $('#erroroccured').show('slow');
                                    $('#errortext').html("Unfortunately, we can't save this right now. Our data service is not responding.  Could you perhaps try again in a few minutes? We're very sorry. Please contact us if this continues to happen.");
                                }
                            },
                            error: function (msg) {
                                $('#serviceloader').hide();
                                $('#<%=txtFindMyCity.ClientID%>:input').attr('disabled', false);
                                $('#erroroccured').show('slow');
                                $('#errortext').html("Unfortunately, we can't save this right now. Perhaps something has gone wrong with some of our data services. Why not try again? If the problem persists, please let us know and we'll get you started.");
                            }
                        });

И, несмотря на это, я всегда получаю { "Response" : "False" }. Я думаю, что это может быть проблема с кешем, но я просто не могу заставить AJAX запустить сервис. Когда я перехожу непосредственно к asset.asmx и вызываю службу, метод CreateCity работает правильно.

Это классический лес для деревьев - я слишком долго на него смотрел и отказываюсь от желания жить ...

Таким образом, вопрос заключается в следующем: Я бы хотел, чтобы служба CreateCity работала правильно, при вызове по $.ajax и не получала ответ { "Response" : "False" }. Может ли кто-нибудь предоставить какое-либо руководство, помощь или содействие в достижении этого с помощью предоставленного мною кода? Пожалуйста, имейте в виду, что я считаю, что мое обслуживание может быть кэшированием (отсюда { "Response" : "False" } ответ) ...

Помощь, советы, пламя и общие комментарии приветствуются ...

Ответы [ 2 ]

1 голос
/ 13 апреля 2011

Вам не нужно вручную JSON сериализовать ответ. Это автоматически обрабатывается службами с поддержкой сценариев. Просто верните строго типизированный объект из вашего веб-метода. То же самое для ввода. Также вы должны убедиться, что URL-адрес правильно закодировал параметры запроса. Итак, начнем с определения моделей:

public class City
{
    public string Cityname { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public decimal Timezoneoffset { get; set; }
    public decimal Lat { get; set; }
    public decimal Lon { get; set; }
}

public class Response
{
    public string Message { get; set; }
    public bool IsSuccess { get; set; }
}

и затем:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Assets : WebService
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(Validation));

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Response CityCreate(City city)
    {
        var response = new Response();

        // ... process and populate the return message, 
        // set the IsSuccess boolean property which will
        // be used by the client (see next...)

        return response;
    }
}

и на стороне клиента:

$.ajax({
    type: 'POST',
    url: '<%= ResolveUrl("~/Assets.asmx/CityCreate") %>',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify({ 
        cityname: $('#<%=litCity.ClientID%>').val(),
        state: $('#<%=litState.ClientID%>').val(),
        country: '<%=Session["BusinessCountry"]%>',
        timezoneoffset: $('#<%=litTimezone.ClientID%>').val(),
        lat: $('#<%=litLat.ClientID%>').val(),
        lon: $('#<%=litLng.ClientID%>').val()
    }),
    success: function (result) {
        // result.d will represent the response so you could:
        if (result.d.IsSuccess) {
             ...
        } else {
             ...
        }
    };
});
0 голосов
/ 13 апреля 2011

Вы можете добавить cache:false к вашему вызову %.ajax, чтобы убедиться, что он не кэшируется.Вы установили точку останова на службе, чтобы дважды проверить, что передается из вашего jQuery?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...