【问题标题】:How to create cross domain asp.net web service如何创建跨域asp.net web服务
【发布时间】:2012-08-27 22:43:56
【问题描述】:

我创建了一个网络服务。我想使用 Ajax jQuery 访问这个 Web 服务。我可以访问同一个域。但我想从另一个域访问此 Web 服务。

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

我的网络服务

[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
});

【问题讨论】:

标签: asp.net ajax web-services cross-domain


【解决方案1】:

使用 jQuery 的 jsonp 数据类型确实是一个不错的选择,因为它可以让跨域脚本编写成为可能……但由于这是 json-with-padding,你必须确保你的 web 服务返回 json..

在此处查看一个好的入门示例:http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

【讨论】:

    【解决方案2】:

    安装 nuget 然后试试这些 这里是 nuget 库上 Json.Net 的链接: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);
    
                } 
            } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-23
      • 2012-09-14
      • 2012-10-14
      • 2013-05-15
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多