调用WebServices的通用方法
问题描述:
我试图做一个方法来控制从我的前端到后端的调用。 要做到这一点,我已经maded一个通用的方法(因为我有很多SoapClients的)调用WebServices的通用方法
public static TRet CallWebServiceAndReturn<TRet, TClient>(ClientBase<TClient> client, string methodName, object[] parameters, bool cacheThis)
where TClient : ClientBase<TClient>
{
//seta retorno para null como default
object ret = null;
//recupera Type da classe
Type clientType = typeof(TClient);
//recupera método da classe para ser executado
MethodInfo method = clientType.GetMethod(methodName);
//cache
if (cacheThis)
{
string cacheKey = CacheManager.GenerateCacheKey(clientType.Name, method.Name, parameters);
if (CacheManager.TryGetFromCacheWS(cacheKey, out ret))
return (TRet)ret;
}
try
{
//tenta executar o método
ret = method.Invoke(client, parameters);
}
catch (Exception)
{
//em caso de erro, fecha conexões
if (client.State == CommunicationState.Faulted)
client.Abort();
else
client.Close();
}
//se cache está habilitado, faaz o cache do resultado da chamada
if (cacheThis)
{
string cacheKey = CacheManager.GenerateCacheKey(clientType.Name, method.Name, parameters);
CacheManager.AddToCacheWS(cacheKey, ret);
}
//converte retorno em RET e retorna
return (TRet)ret;
}
我不真的知道什么是通用TClient必须看起来像。 当我检查从Visual Studio自动生成的客户端,它延伸ClientBase,所以,我的结论是,我只是需要把这个“何处” clausule:
where TClient : ClientBase<TClient>
自动生成的SoapClient的实现:
public partial class MenuSoapClient : System.ServiceModel.ClientBase<frontend.WSMenu.MenuSoap>, frontend.WSMenu.MenuSoap {
在这一点上,我没有任何错误回报,但后来,我尝试一些代码行:
public static CategoryType[] GetSuperiorMenu(int idUser, int idRegion, int idRole, int idLanguage)
{
object[] parameters = new object[] { idUser, idRegion, idRole, idLanguage };
CategoryType[] ret = null;
MenuSoapClient menuClient = new MenuSoapClient();
ret = WSClientService.CallWebServiceAndReturn<CategoryType[], MenuSoapClient>(menuClient, "GetSuperiorMenu", parameters, true);
//rest of my code
在最后一行时,Visual Studio给了我一个犯错或 “menuClient”,第一个参数:
无法转换从frontend.WSMenu.MenuSoapClient到System.ServiceModel.ClientBase
我做错了什么?
在此先感谢。
答
好,具有一定的搜索,我发现这一点: C# generic ClientBase with interface confusion
有一个在我的代码中的一些错误,所以,我改成这样:
public static TRet CallWebServiceAndReturn<TInterface, TClient, TRet>(TClient client, string methodName, object[] parameters, bool cacheThis)
where TInterface : class
where TClient : ClientBase<TInterface>, TInterface
{
//......
}
有这样的一个电话:
MenuSoapClient menuClient = new MenuSoapClient();
ret = WSClientService.CallWebServiceAndReturn<MenuSoap, MenuSoapClient, CategoryType[]>(menuClient, "GetSuperiorMenu", parameters,
true);