最近突然想学习webservice,一直不知道如何跨域调用调用。如果都在同一个项目,相信大家都知道了?特此整理一下关键点,权当学习。
1.WebService 接口编写。这里不在赘述。
步骤:新建web项目=》添加web service=》编写方法接口=》然后发布。
关键如何让外部Ajax 调用。
首先,配置WebService 项目配置文件(web.config)红色部分必须配置,这样第三方才能调用接口方法(经测试通过,直接粘贴就ok),不懂可以百度。
其次,这里贴出WebService 中代码部分,这里我自定义一个返回一个Person集合GetPersonList(),可供Ajax调用。
(1)发布时需要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布以后的域名地址。当然本地测试使用localhost就可以。
(2)要放开[System.Web.Script.Services.ScriptService] 的注释。
以上两步做到写接口发布WebService,访问http://192.168.1.90:5555/XXX.asmx 地址。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebAPI
{
///
/// Summary description for WebService1
///
//[WebService(Namespace = "http://localhost:9999/")]//本地测试可以使用localhost。
[WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布以后的域名地址。
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolBoxItem(false)]
// To allow this Web Service to be called from script,using ASP.NET AJAX,uncomment the following line.
[System.Web.Script.Services.ScriptService]//(AJAX调用必须放开注释)
public class WebService1 : System.Web.Services.WebService
{
[WebMethod(Description = "你好世界")]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string HelloName(string name)
{
return "Hello," + name;
}
[WebMethod]
public List GetPersonList()
{
List lst = new List();
lst.Add(new Person { id = 1,name = "小明",age = 34 });
lst.Add(new Person { id = 1,age = 34 });
return lst;
}
}
public class Person
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
}
3.第三方Ajax调用。我直接返回的是xml格式,当然你也可以在接口中定义返回json(此处取出xml文本并输出在页面)
$(function () {
$.ajax({
type: "POST",//访问WebService使用Post方式请求
//contentType: "application/json;charset=utf-8",//WebService 会返回Json类型
contentType: "application/xml;charset=utf-8",//WebService 会返回xml类型
url: "http://192.168.1.90:5555/WebService1.asmx/GetPersonList",//调用WebService
data: "{}",//Email参数
dataType: 'xml',beforeSend: function (x) { x.setRequestHeader("Content-Type","application/xml; charset=utf-8"); },error: function (x,e) { },success: function (response) { //回调函数,result,返回值
//var json = eval('(' + response.d + ')');
var json = $(response).text();
document.write(json);
// var userid = json.Person.id;
// if (userid > 0) {
// $("#username").html(json.Person.name);
// $("#messagenum").html(json.Person.message);
// }
}
});
});
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。