2011-04-13 82 views
2

我有以下ASMX Web服务: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" }响应)...

帮助,咨询,火焰和欢迎一般性评论...

+0

如果这是MVC我建议你需要一个OutputCache属性/ @指令 - 默认情况下,它假设使用相同参数进行的相同请求应该返回相同的结果,除非您添加元数据以更改该结果。我不知道这些是否适用于ASMXs。 – Rup 2011-04-13 11:40:19

回答

1

您不需要手动JSON序列化响应。这由脚本启用的服务自动处理。只需从Web方法返回一个强类型对象。输入相同。您还必须确保正确地对请求参数进行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

优秀的答案。我会试试看看这是否能解决我遇到的问题。非常感谢;) – dooburt 2011-04-13 11:51:01

+0

绝对真棒的答案。它工作得很好:)谢谢! +1 – dooburt 2011-04-14 10:16:34

0

您可以添加cache:false到您的通话%.ajax以确保它没有被缓存。你有没有在服务上弹出一个断点来仔细检查jQuery中传递的内容?

+0

感谢David的回应,无论是通过VS2010还是通过附加过程,我都无法调试.asmx。这可能与我目前打开的另一个问题有关:http://stackoverflow.com/questions/5611305/visual-studio-2010-debugging-entity-framework-project-throws-entityclient-provide ... Wood for树木大卫,树木为木! :) – dooburt 2011-04-13 11:46:25

+0

不过,我已经使用小提琴来看看传递来来往往,一切似乎完全正常。事实上,我接受请求和它的值,并直接调用服务(/assets.asmx?op=CityCreate),它的工作... – dooburt 2011-04-13 11:47:46

+0

啊,我明白了。对此也发表评论。 :) – DavidGouge 2011-04-13 11:49:40