当前位置:网站首页>Two methods of calling WCF service by C #
Two methods of calling WCF service by C #
2022-07-07 22:17:00 【freelooppowter】
Project brief introduction
Before, the leader assigned me a single sign on function , In fact, the hospital wants to build a unified platform to realize that the unified platform does not need to log in after His、Emr、Lis Wait for the system to log in one by one , You can log in to the corresponding system directly , Then carry out the corresponding operation , Convenient for the daily operation of medical staff . As far as we are concerned His For developers, a login is to call a third party WCF Interface to get the third-party login user in His Login user name 、 The password may also include CA Information .
I have written before WCF The service calls to the third party , Called a third party Http service , I haven't written the call WCF The task of the service . I wrote it myself WCF Service experience plus online information , Two methods are used to realize C# call WCF service :1、 Add service reference directly ;2、 Use Vs Bring their own SvcUtil Tools generate service proxy classes . The editor used is VS2008, There are differences before different versions .
Add service reference directly
First step 、 Right click on the solution project , Select add service reference .
The second step 、 Write the functions that need to be realized , For this project, it is to call the method of the service , Pass in... As required Json Format parameters get and parse the returned Json Format output parameter , Then use the participation to realize the functions you need to realize .
After completing the previous step , You can start writing code to realize the functions you need to realize , Actually add the use of service references ,VS It will automatically add the configuration file corresponding to the solution project referenced by the service for you app.config Add service binding 、 Configuration information such as endpoints . If you write the code that implements the function part under the project that adds the service reference , Then there is no need to manage the configuration file , If your startup project is not a project that adds a service reference , Then you need to add VS The content of the configuration file automatically added by the editor , I will show you the content of the automatic generation part , Because this is the project I quoted in the actual development environment , So I will deal with the path part , The port number is optional , The default port number used by some services . For service binding 、 The endpoint can refer to the blog :https://blog.csdn.net/zhang_xinxiu/article/details/41329511
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISSOService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http:// route [: Port number ]/SSOService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISSOService"
contract="SSOService.ISSOService" name="BasicHttpBinding_ISSOService" />
</client>
</system.serviceModel>
public class SingleSignOnParam
{
public static SingleSignOnOut GetSingleSignOnOut()
{
// Instantiate the service client object
SSOServiceClient client = new SSOServiceClient();
//Json Serialize object instances
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Get machine Mac Address
string StrMac = DbTool.GetMac();
// Build the parameter object
SingleSignOnIn singleSignIn = new SingleSignOnIn() { appid = "34", keyword = StrMac.Replace("-","") };
string jsonStr = string.Empty;
// Serialize to get Json Format input parameter string
jsonStr = serializer.Serialize(singleSignIn);
// Call the service method to get the output parameter string
string StrOut = client.GetDataExchange(jsonStr);
try
{
// Parse the parameter string to get an instance
JsonOutPara para = serializer.Deserialize<JsonOutPara>(StrOut);
if(para.Code=="1")
// The information you need to use is stored in JsonOutPara Object's Result Field , For Json The format string is parsed again
return serializer.Deserialize<SingleSignOnOut>(para.Result);
}
catch (Exception)
{
throw;
}
return null;
}
}
public class SingleSignOnIn
{
public string appid { get; set; }
public string keyword { get; set; }
}
public class JsonOutPara
{
public string Code { get; set; }
public string Message { get; set; }
public string Result { get; set; }
}
public class SingleSignOnOut
{
public string menuid { get; set; }
public string menuname { get; set; }
public string appid { get; set; }
public string appname { get; set; }
public string apptype { get; set; }
}
I made simple comments on the code , If you don't understand, please reply me , Then communicate . There are mainly input and output parameters Json Format string , I'm going to use .Net Self contained System.Web.Extensions Assembly , When using, you need to add references to the project first, and then add namespaces in front of the code , The code is as follows :using System.Web.Script.Serialization; about Json For details of converting to objects, please refer to blog articles https://www.cnblogs.com/zxtceq/p/6610214.html, The article also gives a transformation Json String to C# Class , I think it's great .
Generate proxy class
The method of generating proxy classes has certain advantages over the first method : There is no need to add service references , But the contents of the configuration file still need to be added , But once the service is updated , You must regenerate the new proxy class and replace it , I'm going to use Vs2008 Self contained SvcUtil Tools , Enter the command after starting the program : svcutil.exe http:// route [: port ]/SSOService.svc?wsdl
Next, find the agent class file and configuration file under the corresponding directory , Paste the contents of the configuration file into the configuration file of the actually started project . I tested this method in a separate program , The actual effect is consistent with adding service references directly . Open Alipay home search “524252978”, You can get a red envelope .
Reference material :
边栏推荐
- An in-depth understanding of fp/fn/precision/recall
- OpenGL configuration vs2019
- What is the difference between the three values of null Nan undefined in JS
- How does win11 unblock the keyboard? Method of unlocking keyboard in win11
- null == undefined
- L2: current situation, prospects and pain points of ZK Rollup
- Kirin Xin'an operating system derivative solution | storage multipath management system, effectively improving the reliability of data transmission
- #DAYU200体验官#MPPT光伏发电项目 DAYU200、Hi3861、华为云IotDA
- Crawler (17) - Interview (2) | crawler interview question bank
- Overseas agent recommendation
猜你喜欢
NVR hard disk video recorder is connected to easycvr through the national standard gb28181 protocol. What is the reason why the device channel information is not displayed?
PDF文档签名指南
Node:504 error reporting
OpenGL configuration vs2019
Build your own website (18)
Use camunda to do workflow design and reject operations
Reinforcement learning - learning notes 9 | multi step TD target
Wechat official account oauth2.0 authorizes login and displays user information
Matplotlib drawing interface settings
Solve the problem of uni in uni app Request sent a post request without response.
随机推荐
Pdf document signature Guide
The difference between NPM uninstall and RM direct deletion
Crawler (17) - Interview (2) | crawler interview question bank
How to choose the appropriate automated testing tools?
【Azure微服务 Service Fabric 】因证书过期导致Service Fabric集群挂掉(升级无法完成,节点不可用)
强化学习-学习笔记9 | Multi-Step-TD-Target
Song list 11111
ByteDance Android interview, summary of knowledge points + analysis of interview questions
解决uni-app中uni.request发送POST请求没有反应。
Debugging and handling the problem of jamming for about 30s during SSH login
NVR硬盤錄像機通過國標GB28181協議接入EasyCVR,設備通道信息不顯示是什麼原因?
The maximum number of meetings you can attend [greedy + priority queue]
【colmap】稀疏重建转为MVSNet格式输入
Take the intersection of two sets
Reinforcement learning - learning notes 9 | multi step TD target
The essence of analog Servlet
#DAYU200体验官#MPPT光伏发电项目 DAYU200、Hi3861、华为云IotDA
MIT6.S081-Lab9 FS [2021Fall]
PKPM 2020 software installation package download and installation tutorial
Oracle advanced (VI) Oracle expdp/impdp details