二开案例.自定义WebApi,获取Post/Get传递的数据,用于接受第三方推送原创
10人赞赏了该文章
415次浏览
编辑于2024年08月09日 09:14:42
问题:
自定义webapi怎么接收HTTP请求推送,Post方法,ContentType 为“application/x-www-form-urlencoded”。的参数
解决方案:
1、创建一个无参数的自定义WebApi方法,例如Jac.XkDemo.BOS.WebApi.TestWebApiService.Test;
2、第三方调用接口 /k3cloud/Jac.XkDemo.BOS.WebApi.TestWebApiService.Test,Test24.PlugIns.BL.common.kdsvc
通过Header或Cookie传递SessionId
3、在自定义WebApi方法中通过HttpContext.Current.Request获取传参和SessionId,创建Context。
WebApi代码:
using Kingdee.BOS.ServiceFacade.KDServiceFx; using Kingdee.BOS.WebApi.ServicesStub; using System.Text; using System.Web; namespace Jac.XkDemo.BOS.WebApi { /// <summary> /// 【WebApi】自定义WebApi接口 /// </summary> [Kingdee.BOS.Util.HotUpdate] public class TestWebApiService: AbstractWebApiBusinessService { public TestWebApiService(KDServiceContext context) : base(context) { } const string kd_sessionid_key = "kdservice-sessionid"; public object Test() { //通过HttpPost传参时,this.KDContext.Session.AppContext为null,需要自行从Header或Cookie中拿到kdservice-sessionid,创建Context StringBuilder sb = new StringBuilder(); foreach (var key in HttpContext.Current.Request.Form.Keys) { sb.AppendFormat("{0}={1}\r\n", key, HttpContext.Current.Request.Form[key.ToString()]); } var kd_sessionid = HttpContext.Current.Request.Headers[kd_sessionid_key]; if (!string.IsNullOrWhiteSpace(kd_sessionid)) { // 获取登录用户会话信息 var userSession = SessionManager.GetCurrentSession(kd_sessionid); if (userSession != null) { // 获取登录用户上下文 var userContext = userSession.AppContext; sb.AppendLine("当前用户:" + userContext.UserName); } } return sb.ToString(); } } }
调用端代码:
void Main() { var jser = new System.Web.Script.Serialization.JavaScriptSerializer(); var loginResult = InvokeHelper.Login(); Console.WriteLine(loginResult); var json = jser.Serialize(new object[] { }); //正常的WebApi调用 var result = InvokeHelper.Call("Jac.XkDemo.BOS.WebApi.TestWebApiService.Test,Test24.PlugIns.BL.common.kdsvc", new object[] { }); Console.WriteLine(result); //Post调用 WebClient wc = new WebClient(); string url = "http://localhost/k3cloud/Jac.XkDemo.BOS.WebApi.TestWebApiService.Test,Test24.PlugIns.BL.common.kdsvc"; wc.Encoding = Encoding.UTF8; wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); wc.Headers.Add("kdservice-sessionid", "c40e4b13-ce34-4d4f-9f48-ddc1ab4697e4"); string result2 = wc.UploadString(url, "userName=admin&pwd=123456"); Console.WriteLine(result2); } public static class InvokeHelper { private static string CloudUrl = "http://localhost/k3cloud/"; public static string Login() { HttpClient httpClient = new HttpClient(); httpClient.Url = string.Concat(CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc"); List<object> Parameters = new List<object>(); Parameters.Add("664cc733b161a9");// Parameters.Add("cc");//用户 Parameters.Add("888888");//密码 Parameters.Add(2052); var jser = new System.Web.Script.Serialization.JavaScriptSerializer(); httpClient.Content = jser.Serialize(Parameters).Dump("login send content"); return httpClient.SysncRequest(); } public static string Call(string detailAddress, object[] paras) { var jsonInputParam = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(paras); HttpClient httpClient = new HttpClient(); httpClient.Url = CloudUrl + detailAddress; httpClient.Content = jsonInputParam; string jsonOutputParam = httpClient.SysncRequest(); return jsonOutputParam; } } class HttpClient { /// <summary> /// Seivice URL /// </summary> public string Url { get; set; } /// <summary> /// 内容 /// </summary> public string Content { get; set; } /// <summary> /// Cookie,保证登录后,所有访问持有一个Cookie; /// </summary> static CookieContainer Cookie = new CookieContainer(); /// <summary> /// HTTP访问 /// </summary> public string SysncRequest() { HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest; httpRequest.Method = "POST"; httpRequest.ContentType = "application/json"; httpRequest.CookieContainer = Cookie; httpRequest.Timeout = 1000 * 60 * 10;//10min using (Stream reqStream = httpRequest.GetRequestStream()) { Dictionary<string, object> jObj = new Dictionary<string, object>(); jObj.Add("format", 1); jObj.Add("useragent", "ApiClient"); jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString()); jObj.Add("parameters", Content); jObj.Add("timestamp", DateTime.Now); jObj.Add("v", "1.0"); //string sContent = jObj.ToString(); string sContent = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(jObj); var bytes = UnicodeEncoding.UTF8.GetBytes(sContent); reqStream.Write(bytes, 0, bytes.Length); reqStream.Flush(); } using (var repStream = httpRequest.GetResponse().GetResponseStream()) { using (var reader = new StreamReader(repStream)) { return ValidateResult(reader.ReadToEnd()); } } } private static string ValidateResult(string responseText) { if (responseText.StartsWith("response_error:")) { var failText = responseText.TrimStart("response_error:".ToCharArray()); } return responseText; } }
赞 10
10人点赞
还没有人点赞,快来当第一个点赞的人吧!
打赏
0人打赏
还没有人打赏,快来当第一个打赏的人吧!
推荐阅读