一、C#WebService跨域问题
Web.config中system.web节点下添加
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> <add name="HttpSoap"/> <add name="Documentation"/> </protocols> </webServices>
configuration节点下添加
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/> <add name="Access-Control-Allow-Origin" value="*"/> </customHeaders> </httpProtocol> </system.webServer>
二、ajax请求webservice
html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-3.3.1.min.js" ></script> <script type="text/javascript"> $(function(){ /*无参*/ $("#btnHelloWorld").click(function(){ $.ajax({ type: "POST", contentType:"application/json", url:"http://localhost:53029/WebService1.asmx/HelloWorld", data:"{}", dataType:'json', success:function(result){ alert(result.d); } }); }); /*传入1个参数*/ $("#btnHello").click(function(){ $.ajax({ type: "POST", contentType:"application/json", url:"http://localhost:53029/WebService1.asmx/Hello", data:"{name:'KiMoGiGi'}", dataType:'json', success:function(result){ alert(result.d); } }); }); /*返回泛型列表*/ $("#btnArray").click(function(){ $.ajax({ type: "POST", contentType:"application/json", url:"http://localhost:53029/WebService1.asmx/CreateArray", data:"{i:10}", dataType:'json', success:function(result){ alert(result.d.join(" | ")); } }); }); /*返回复杂类型*/ $("#btnPerson").click(function(){ $.ajax({ type: "POST", contentType:"application/json", url:"http://localhost:53029/WebService1.asmx/GetPerson", data:"{name:'张三',age:26}", dataType:'json', success:function(result){ var person = result.d; var showText = []; for(var p in person){ showText.push(p + ":" + person[p]); } alert(showText.join("/r/n")); } }); }); }); </script> </head> <body> <input type="button" id="btnHelloWorld" value="HelloWorld" /> <input type="button" id="btnHello" value="Hello" /> <input type="button" id="btnArray" value="CreateArray" /> <input type="button" id="btnPerson" value="GetPerson" /> </body> </html>
webservice后台代码:
/// <summary> /// WebService1 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] // 令WebService成功传入Json参数,并以Json形式返回结果 [GenerateScriptType(typeof(Person))] // 不是必要,但推荐添加(如果Person里面再嵌套另一个复杂类型,则必要声明) [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { /// 无任何参数 [WebMethod] public string HelloWorld() { return " Hello World "; } /// 传入参数 [WebMethod] public string Hello(string name) { return string.Format(" Hello {0} ", name); } /// 返回泛型列表 [WebMethod] public List<int> CreateArray(int i) { List<int> list = new List<int>(); while (i >= 0) { list.Add(i--); } return list; } /// 返回复杂类型 [WebMethod] public Person GetPerson(string name, int age) { return new Person() { Name = name, Age = age }; } } /// 复杂类型 public class Person { public string Name { get; set; } public int Age { get; set; } }
三、webservice的SoapHeader访问验证
1、创建一个实体类AuthorizeHeader 继承【System.Web.Services.Protocols】SoapHeader
/// <summary> /// 头部账号密码验证 /// </summary> public class AuthorizeHeader: SoapHeader { public string username { get; set; } public string password { get; set; } }
webservice更改
/// <summary> /// PubWebService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [System.Web.Script.Services.ScriptService] public class PubWebService : System.Web.Services.WebService { public AuthorizeHeader authHeader = null; [WebMethod(Description = "测试调用验证")] [SoapHeader("authHeader")] public string HelloWord() { if (authHeader == null || !ValidateUser(authHeader.username,authHeader.password)) return "无访问权限"; return "Hello Word!"; } private bool ValidateUser(string username, string password) { if (username == "admin" && password == "123456") return true; return false; } }
使用posman访问:
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <AuthorizeHeader xmlns="http://tempuri.org/"> <username>admin</username> <password>123456</password> </AuthorizeHeader> </soap:Header> <soap:Body> <GetRegionData xmlns="http://tempuri.org/" /> </soap:Body> </soap:Envelope>
调用:
private void button1_Click(object sender, EventArgs e) { string url = "http://localhost:8889/PubWebService.asmx?wsdl"; PubWebService pubWebService = new PubWebService(); pubWebService.Url = url; AuthorizeHeader authorizeHeader = new AuthorizeHeader(); authorizeHeader.username = "admin"; authorizeHeader.password = "123456"; pubWebService.AuthorizeHeaderValue= authorizeHeader; string josnStr=pubWebService.HelloWord(); }
2、使用posman测试 Basic Auth 认证
对应生成了头部信息:
代码分享:
using System.Web;//传递头部参数需要引用 if (HttpContext.Current.Request.Headers.ContainsKey("Authorization")) { var authorize = HttpContext.Current.Request.Headers["Authorization"].ToString(); if (authorize.Contains("Basic"))//如果是Basic 身份认证 { var info = authorize.Replace("Basic ", string.Empty); var bytes = Convert.FromBase64String(info);//反解析Basic 64 var contents = Encoding.Default.GetString(bytes); var dd = contents.Split(":").ToArray(); var userName = dd[0];//用户名 var userPwd = dd[1];//密码 if (userName == "GeBiLaoWang" && userPwd == "123456") { return "无访问权限"; } } }
使用窗体调用
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { #region 方法一 string url = "http://localhost:52932/PubWebService.asmx/MethodName"; string strParams = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //请求方式POST request.Method = "POST"; //传输数据JSON类型 request.ContentType = "application/json;charset=utf-8"; request.Credentials = CredentialCache.DefaultCredentials;//获取应用程序的系统凭据。 string visitAuthorized = AESHelper.Encrypt("admin:123456"); request.Headers.Add("VisitAuthorized", visitAuthorized); //请求超时时间,10分钟 request.Timeout = 600000; //写入数据 var data = Encoding.UTF8.GetBytes(strParams); request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); //请求返回数据 StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8); string ret = reader.ReadToEnd(); reader.Close(); //解析josn ReturnData<List<Sys_Region>> returnData = JsonConvert.DeserializeObject<ReturnData<List<Sys_Region>>>(ret); #endregion } } public class ReturnData<T> { public string code { get; set; } public string msg { get; set; } public T data { get; set; } } public class Sys_Region { public System.Guid region_id { get; set; } public Nullable<System.Guid> region_pid { get; set; } public string region_name { get; set; } public string region_code { get; set; } public string region_type { get; set; } public Nullable<decimal> region_sort { get; set; } } }