如何在 C# 中调用 Web 服务

     2023-03-31     279

关键词:

【中文标题】如何在 C# 中调用 Web 服务【英文标题】:How to call web Services in C# 【发布时间】:2021-01-06 00:29:36 【问题描述】:

我正在调用 Web 服务并返回列表,但我不能这样做。 我想将下拉列表与 Web 服务绑定。

我添加了 INITIATORS_LIST 类,其中包含我想在下拉列表中绑定的所有字段,例如公司、国家、部门、位置......等等。请问我该如何实现我可以接受的任何替代方法?

示例 JSON 数据

"Companies":["ACTIVE":true,"COMPANY_ID":1,"CompanyCode":"1000","CompanyName":"Almarai Company","CountryCode":"SAU","CountryName":"Saudi Arabia","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","ACTIVE":true,"COMPANY_ID":6,"CompanyCode":"4000","CompanyName":"Almarai Co. Bahrain WLL","CountryCode":"BAH","CountryName":"Bahrain","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","ACTIVE":true,"COMPANY_ID":8,"CompanyCode":"5000","CompanyName":"Bustan Al Khaleej Est.","CountryCode":"UAE","CountryName":"United Arab Emirates","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","ACTIVE":true,"COMPANY_ID":11,"CompanyCode":"5200","CompanyName":"ALMARAI EMIRATES COMPANY L.L.C","CountryCode":"UAE","CountryName":"United Arab Emirates","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","ACTIVE":true,"COMPANY_ID":15,"CompanyCode":"6000","CompanyName":"Al Kharafi Brothers","CountryCode":"KWT","CountryName":"Kuwait","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","ACTIVE":true,"COMPANY_ID":18,"CompanyCode":"7000","CompanyName":"Ar*** Planets Company","CountryCode":"OMN","CountryName":"Oman","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales"],"Countries":["COUNTRY_ACTIVE":true,"COUNTRY_M_ID":1,"CountryCode":"SAU","CountryName":"Saudi Arabia","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","COUNTRY_ACTIVE":true,"COUNTRY_M_ID":3,"CountryCode":"UAE","CountryName":"United Arab Emirates","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","COUNTRY_ACTIVE":true,"COUNTRY_M_ID":4,"CountryCode":"BAH","CountryName":"Bahrain","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","COUNTRY_ACTIVE":true,"COUNTRY_M_ID":5,"CountryCode":"OMN","CountryName":"Oman","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","COUNTRY_ACTIVE":true,"COUNTRY_M_ID":7,"CountryCode":"KWT","CountryName":"Kuwait","DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales"],"Divisions":["ACTIVE":true,"CompanyCode":null,"CompanyName":null,"CountryCode":null,"CountryName":null,"DB_CONNECTION_STRING":null,"DivisionCode":"1000","DivisionId":1,"DivisionName":"Sales","WEB_URL":null],"Locations":

ALM_COUNTRY_M 类:

 public partial class ALM_COUNTRY_M : object, System.Runtime.Serialization.IExtensibleDataObject, 
        System.ComponentModel.INotifyPropertyChanged 
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private bool COUNTRY_ACTIVEField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private int COUNTRY_M_IDField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string CountryCodeField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string CountryNameField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string DivisionCodeField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private int DivisionIdField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string DivisionNameField;
        
        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData 
            get 
                return this.extensionDataField;
            
            set 
                this.extensionDataField = value;
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public bool COUNTRY_ACTIVE 
            get 
                return this.COUNTRY_ACTIVEField;
            
            set 
                if ((this.COUNTRY_ACTIVEField.Equals(value) != true)) 
                    this.COUNTRY_ACTIVEField = value;
                    this.RaisePropertyChanged("COUNTRY_ACTIVE");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public int COUNTRY_M_ID 
            get 
                return this.COUNTRY_M_IDField;
            
            set 
                if ((this.COUNTRY_M_IDField.Equals(value) != true)) 
                    this.COUNTRY_M_IDField = value;
                    this.RaisePropertyChanged("COUNTRY_M_ID");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string CountryCode 
            get 
                return this.CountryCodeField;
            
            set 
                if ((object.ReferenceEquals(this.CountryCodeField, value) != true)) 
                    this.CountryCodeField = value;
                    this.RaisePropertyChanged("CountryCode");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string CountryName 
            get 
                return this.CountryNameField;
            
            set 
                if ((object.ReferenceEquals(this.CountryNameField, value) != true)) 
                    this.CountryNameField = value;
                    this.RaisePropertyChanged("CountryName");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string DivisionCode 
            get 
                return this.DivisionCodeField;
            
            set 
                if ((object.ReferenceEquals(this.DivisionCodeField, value) != true)) 
                    this.DivisionCodeField = value;
                    this.RaisePropertyChanged("DivisionCode");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public int DivisionId 
            get 
                return this.DivisionIdField;
            
            set 
                if ((this.DivisionIdField.Equals(value) != true)) 
                    this.DivisionIdField = value;
                    this.RaisePropertyChanged("DivisionId");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string DivisionName 
            get 
                return this.DivisionNameField;
            
            set 
                if ((object.ReferenceEquals(this.DivisionNameField, value) != true)) 
                    this.DivisionNameField = value;
                    this.RaisePropertyChanged("DivisionName");
                
            
        
        
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        
        protected void RaisePropertyChanged(string propertyName) 
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) 
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            
        
    

INITIATORS_LIST 类:

public partial class INITIATORS_LIST : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged 
        
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] CompaniesField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.ALM_COUNTRY_M[] CountriesField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M[] DivisionsField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.LOCATION[] LocationsField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.REGION[] RegionsField;
        
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private Almarai.GiveAway.GetInitiatorList.ALM_WKFLW_TYPE_M[] WorkflowTypesField;
        
        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData 
            get 
                return this.extensionDataField;
            
            set 
                this.extensionDataField = value;
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] Companies 
            get 
                return this.CompaniesField;
            
            set 
                if ((object.ReferenceEquals(this.CompaniesField, value) != true)) 
                    this.CompaniesField = value;
                    this.RaisePropertyChanged("Companies");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.ALM_COUNTRY_M[] Countries 
            get 
                return this.CountriesField;
            
            set 
                if ((object.ReferenceEquals(this.CountriesField, value) != true)) 
                    this.CountriesField = value;
                    this.RaisePropertyChanged("Countries");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M[] Divisions 
            get 
                return this.DivisionsField;
            
            set 
                if ((object.ReferenceEquals(this.DivisionsField, value) != true)) 
                    this.DivisionsField = value;
                    this.RaisePropertyChanged("Divisions");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.LOCATION[] Locations 
            get 
                return this.LocationsField;
            
            set 
                if ((object.ReferenceEquals(this.LocationsField, value) != true)) 
                    this.LocationsField = value;
                    this.RaisePropertyChanged("Locations");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.REGION[] Regions 
            get 
                return this.RegionsField;
            
            set 
                if ((object.ReferenceEquals(this.RegionsField, value) != true)) 
                    this.RegionsField = value;
                    this.RaisePropertyChanged("Regions");
                
            
        
        
        [System.Runtime.Serialization.DataMemberAttribute()]
        public Almarai.GiveAway.GetInitiatorList.ALM_WKFLW_TYPE_M[] WorkflowTypes 
            get 
                return this.WorkflowTypesField;
            
            set 
                if ((object.ReferenceEquals(this.WorkflowTypesField, value) != true)) 
                    this.WorkflowTypesField = value;
                    this.RaisePropertyChanged("WorkflowTypes");
                
            
        
        
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        
        protected void RaisePropertyChanged(string propertyName) 
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) 
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            
        
    

参考:

public Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST GetInitiatorsListByWorkflow(string userId, string WorkflowTypeCode) 
            return base.Channel.GetInitiatorsListByWorkflow(userId, WorkflowTypeCode);
        

[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMasterDataService/GetInitiatorsListByWorkflow", ReplyAction="http://tempuri.org/IMasterDataService/GetInitiatorsListByWorkflowResponse")]
        [System.ServiceModel.FaultContractAttribute(typeof(Almarai.GiveAway.GetInitiatorList.CustomFaultException), Action="http://tempuri.org/IMasterDataService/GetInitiatorsListByWorkflowCustomFaultExcep" +
            "tionFault", Name="CustomFaultException", Namespace="http://schemas.datacontract.org/2004/07/Almarai.Web.Services.MasterData")]
        Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST GetInitiatorsListByWorkflow(string userId, string WorkflowTypeCode);

国家类:(我是否应该为公司、国家、地区等每个不同的字段更改此类)

public class CountryList
        
            public CountryList(INITIATORS_LIST data)
            
                ExtensionData = data;
            

            public INITIATORS_LIST ExtensionData  get; internal set; 
        

我的方法:(我应该如何修改我的方法)

 [WebMethod]
        public static List<CountryList> GetCountriesName(string UserID)
        
            GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
            string userid = "approver01";
            string work = "4";
            List<CountryList> countries = oClient.GetInitiatorsListByWorkflow(userid, work); // Error on this line 

            foreach (Country c in countries)
            
                lst.Add(c.Name);
            

            return lst; //Error on this line
        

我无法添加到列表中还有其他方法吗? 我知道由于返回类型我无法做到,但是

【问题讨论】:

评论不用于扩展讨论;这个对话是moved to chat。 【参考方案1】:

GetInitiatorsListByWorkflow 方法返回 Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST 对象,而不是 List&lt;CountryList&gt;。同样,您的 GetCountriesName 方法返回 List&lt;CountryList&gt;,而不是您的(在显示的代码中未定义)lst 变量的类型。这就是你有错误的原因 - 你不能只是随机地将对象分配给错误类型的变量。

无论如何,对于您的国家/地区列表,您实际上希望使用 ALM_COUNTRY_M 类中的两个属性。 INITIATORS_LIST 包含该类型的对象数组。

所以你真正需要做的是从GetInitiatorsListByWorkflow 方法返回的INITIATORS_LIST 中获取ALM_COUNTRY_M 对象的数组,然后循环遍历它们,并为每个对象创建一个CountryList 的等效实例,使用 ALM_COUNTRY_M 对象中的值设置其属性,并将其添加到要返回的列表中。

类似这样的东西(未经测试):

[WebMethod]
public static List<CountryList> GetCountriesName(string UserID)

    GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
    string userid = "approver01";
    string work = "4";

    Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST initiatorsList = oClient.GetInitiatorsListByWorkflow(userid, work); //get data from webservice
    Almarai.GiveAway.GetInitiatorList.ALM_COUNTRY_M[] countryMList = initiatorsList.Countries; //get list of countries from the data returned by the webservice

    List<CountryList> countries = new List<CountryList>(); //create an empty list which will be populated with data from the webservice

    //loop through list of countries returned from webservice
    foreach (Almarai.GiveAway.GetInitiatorList.ALM_COUNTRY_M country in countryMList)
    
       //add new instance of CountryList using fields from the webservice class
       countries.Add(new CountryList() 
         CountryCode = country.CountryCode,
         CountryName = country.CountryName
       );
    

    return countries; //return the completed list of countries

CountryList 类的定义应该更像这样:

public class CountryList

    public string CountryCode  get; set; 
    public string CountryName  get; set; 


附:将CountryList 类重命名为Country 会更有意义,因为每个对象只代表一个国家。它是定义列表的List&lt;&gt; 部分。但这是一个由您决定的单独问题。

【讨论】:

创建 Restful Web 服务以在 C# 中调用存储过程

...edprocedureinC#【发布时间】:2021-08-2106:02:38【问题描述】:如何在VisualStudio2019中创建RestfulWeb服务以调用存储过程。我尝试使用SOAP和WCFWeb服务,但我不知道如何使用RESTfulWeb服务。我需要在URI模板中提供什么?请提供任何示例 查看详情

从 C# .NET Core(特别是 Workday)调用 Java Web 服务。如何在soap请求中获取xml属性

】从C#.NETCore(特别是Workday)调用JavaWeb服务。如何在soap请求中获取xml属性【英文标题】:CallingaJavawebservicefromC#.NETCore(specificallyWorkday).Howtogetxmlattributesinthesoaprequest【发布时间】:2021-12-1300:23:33【问题描述】:我正在尝试在.netcorec... 查看详情

如何在我的可视 C# Web 服务中为我的 android 应用程序调用 LINQ 中的用户定义函数?

】如何在我的可视C#Web服务中为我的android应用程序调用LINQ中的用户定义函数?【英文标题】:HowtocalluserdefinedfunctioninLINQinmyvisualC#webserviceformyandroidapplication?【发布时间】:2012-03-2014:52:40【问题描述】:我目前正在开发一个应用程... 查看详情

在 Web 服务 WCF 中调用 Web 服务

】在Web服务WCF中调用Web服务【英文标题】:CallingWebserviceinsidewebserviceWCF【发布时间】:2014-08-2310:01:23【问题描述】:我正在开发一个SOAP项目,其中包含:C#客户端C#服务器(WCF)J2EE服务器(带web服务)在我的C#服务器上,我有我的se... 查看详情

如何调用从 Web 服务返回数组的函数?

】如何调用从Web服务返回数组的函数?【英文标题】:Howtocallafunctionthatreturnsanarrayfromawebservice?【发布时间】:2012-12-1919:24:46【问题描述】:我是C#新手,我正在使用nuSOAP和PHP。我在一个返回数组的Web服务中编写了一个函数。问题... 查看详情

如何从 c# web 服务调用 c++ Opencv 项目?

】如何从c#web服务调用c++Opencv项目?【英文标题】:Howtocallc++Oppencvprojectfromc#webservice?【发布时间】:2012-06-0615:41:15【问题描述】:我已经将图像识别算法实现为OpenCVc++项目,并且我有C#web服务。我想从我的c#web服务调用我的c++Openc... 查看详情

如何在 C# 中更改soap xml Web 服务?

】如何在C#中更改soapxmlWeb服务?【英文标题】:HowIchangesoapxmlwebserviceinc#?【发布时间】:2018-12-1706:44:20【问题描述】:我使用了webservice首选项cs代码。我有soapxmlweb服务请求。<s:Envelopexmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><... 查看详情

要在 C# 中使用 RESTful Web 服务,我应该使用 HttpWebRequest 吗?

...HttpWebRequest?【发布时间】:2010-11-3021:48:37【问题描述】:如何在C#代码中使用RESTfulWeb服务?注意:我所说的RESTful是指非SOAP。例如,在flickrAPI中,您可以按如下方式调用其Web服务以返回JSO 查看详情

如何使用 SMO 在存储过程中调用 c# 函数?

】如何使用SMO在存储过程中调用c#函数?【英文标题】:Howtocallc#functioninstoredprocedurewithSMO?【发布时间】:2021-08-2213:23:10【问题描述】:我在C#中设计了一个Migrate()方法来将一些SQL对象从一台服务器传输到另一台服务器,我想将它... 查看详情

如何使用 ASP.NET C# 在使用 ajax 完成 Web 服务时生成警报

】如何使用ASP.NETC#在使用ajax完成Web服务时生成警报【英文标题】:HowtogeneratealertoncompletionofwebservicewithajaxusingASP.NETC#【发布时间】:2021-04-2115:00:44【问题描述】:我不确定是否可以做我要求的事情(花了一些时间研究它但没有成... 查看详情

有啥方法可以保护在开源项目中进行的 Web 服务调用? [关闭]

】有啥方法可以保护在开源项目中进行的Web服务调用?[关闭]【英文标题】:Anywaytosecureawebservicecallmadeinanopen-sourceproject?[closed]有什么方法可以保护在开源项目中进行的Web服务调用?[关闭]【发布时间】:2011-12-2216:59:10【问题描述... 查看详情

调用 https 网络服务 (C#)

...ps”无效;预期为“http”。我在网上搜索过,但我不确定如何解决?是否可以通过向Web服务添加一些代码来解决?谢谢:-)【问题讨论】:你是用WC 查看详情

如何在 IIS 托管的 C# web 服务中强制访问控制允许来源

】如何在IIS托管的C#web服务中强制访问控制允许来源【英文标题】:HowtoforceAccess-Control-Allow-OrigininanIIShostedC#webservice【发布时间】:2019-09-0518:01:10【问题描述】:我在IIS10中托管了一个.net网络服务。我正在尝试从Angular前端的网络... 查看详情

如何在c#中webservice调用方法总结

 一、WebService在cs后台程序中的调用  A、通过命名空间和类名直接调用  示例:  WebServicews=newWebService();  strings=ws.HelloWorld();  B、通过添加WEB引用的方式调用,首先添加WEB引用,通过URL指向WEBSERVICE,  指定WEB引用... 查看详情

如何在 Android 中保护调用 web 服务

】如何在Android中保护调用web服务【英文标题】:HowtosecurecallingwebserviceinAndroid【发布时间】:2014-10-1919:27:35【问题描述】:您好,我正在开发android应用程序,在该应用程序中我需要执行一些httpsWeb服务,因此我所有的Web服务URL和W... 查看详情

如何在 C# 中调用跨域 API

】如何在C#中调用跨域API【英文标题】:HowtocallCrossdomainAPIinc#【发布时间】:2016-08-0111:45:00【问题描述】:我需要使用C#调用不同服务器的API。我正在使用以下方法using(HttpClientclient=newHttpClient())client.DefaultRequestHeaders.Authorization=newA... 查看详情

C# Web 服务模拟

...应用程序,应用的模拟可能应用于工作线程,而不是实际调用该方法的线程...我想您可能会收到拒绝访问错误...没有问题地进行模拟..只需在webconfig中启用它即可..我必须对我的功能进行哪些更改 查看详情

如何在 Asp.net C# 中调用 webmethod

】如何在Asp.netC#中调用webmethod【英文标题】:HowtocallwebmethodinAsp.netC#【发布时间】:2013-10-0706:11:15【问题描述】:我想使用下面的代码在asp.netc#应用程序中调用一个web方法Jquery:jQuery.ajax(url:\'AddToCart.aspx/AddTo_Cart\',type:"POST",data:"\'q... 查看详情