当前位置:网站首页>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 :
边栏推荐
- SAR image quality evaluation
- Oracle advanced (VI) Oracle expdp/impdp details
- PDF文档签名指南
- 【JDBC Part 1】概述、获取连接、CRUD
- ByteDance Android interview, summary of knowledge points + analysis of interview questions
- Two kinds of updates lost and Solutions
- Restore backup data on persistent volumes
- Crawler (17) - Interview (2) | crawler interview question bank
- 100million single men and women "online dating", supporting 13billion IPOs
- SAR影像质量评估
猜你喜欢
Have you ever been confused? Once a test / development programmer, ignorant gadget C bird upgrade
How to quickly check whether the opening area ratio of steel mesh conforms to ipc7525
Jerry's test box configuration channel [chapter]
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?
谈谈制造企业如何制定敏捷的数字化转型策略
【Azure微服务 Service Fabric 】如何转移Service Fabric集群中的种子节点(Seed Node)
How to make agile digital transformation strategy for manufacturing enterprises
Reptile combat (VII): pictures of the king of reptiles' heroes
使用 CustomPaint 绘制基本图形
Jerry's about TWS pairing mode configuration [chapter]
随机推荐
Ternary expressions, generative expressions, anonymous functions
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?
Which futures company is the safest to open a futures account?
Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)
OpenGL job coordinate system
Nine degree 1201 - traversal of binary sort number - binary sort tree "suggestions collection"
PKPM 2020软件安装包下载及安装教程
Application practice | the efficiency of the data warehouse system has been comprehensively improved! Data warehouse construction based on Apache Doris in Tongcheng digital Department
Automatic classification of defective photovoltaic module cells in electronic images
Matplotlib drawing interface settings
ByteDance Android interview, summary of knowledge points + analysis of interview questions
OpenGL homework - Hello, triangle
Take the intersection of two sets
Restapi version control strategy [eolink translation]
Why can't win11 display seconds? How to solve the problem that win11 time does not display seconds?
Jerry's key to initiate pairing [chapter]
How to write an augmented matrix into TXT file
Crawler (17) - Interview (2) | crawler interview question bank
OpenGL jobs - shaders
Tcp/ip protocol stack