2012-09-03 133 views
1

我已经创建了一个web服务。我想使用Ajax jQuery访问这个Web服务。我可以在同一个域上访问。但我想从另一个域访问这个Web服务。如何创建跨域asp.net web服务

有没有人有一个想法如何在asp.net中创建一个跨域Web服务?在web.config文件中的任何设置,以便我从另一个域访问它?

我的web服务

[WebService(Namespace = "http://tempuri.org/")] 
[System.Web.Script.Services.ScriptService] 
public class Service : System.Web.Services.WebService 
{ 
    public Service() { 
    } 

    [WebMethod] 
    public string SetName(string name) { 
     return "hello my dear friend " + name; 

    } 
} 

的JavaScript

$.ajax({ 
    type: "GET", 
    url:'http://192.168.1.119/Service/SetName.asmx?name=pr', 
    ContentType: "application/x-www-form-urlencoded", 
    cache: false, 
    dataType: "jsonp", 
    success: onSuccess 
}); 
+1

请按照这个线程 http://stackoverflow.com/questions/861784/how-to-call-a-web-service-from-jquery –

+0

也可以使用http://stackoverflow.com/questions/230401/how -to-的用jQuery的通话-AN-ASP网的Web服务 –

回答

0

安装的NuGet,然后尝试这些 这里是Json.Net对的NuGet库的链接:nuget.org/packages/Newtonsoft。 Json

using Json; 
using Newtonsoft.Json; 
using System.Xml.Serialization; 


    [WebService(Namespace = "http://tempuri.org/")] 
     [System.Web.Script.Services.ScriptService] 
     public class Service : System.Web.Services.WebService 
     { 
      public Service() { 
      } 

      [WebMethod] 
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
      public string SetName(string name) { 
     return JsonConvert.SerializeObject("hello my dear friend " + name, Newtonsoft.Json.Formatting.Indented); 

      } 
     }