当前位置:网站首页>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 :

https://www.cnblogs.com/pnljs/p/3765892.html

https://www.cnblogs.com/zxtceq/p/6610214.html

原网站

版权声明
本文为[freelooppowter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130607228536.html