WebService经验分享

  Webservice是我们常用的用来向客户端提供的访问数据的接口,在客户端添加对webservice的引用以后,在客户端就会生成Webservice在本地的代理,然后客户端就可以像使用本地的类一样使用Webservice的代理类了。当然生成的本地代理和原生的Webservice提供的访问方法还是有点区别的,如WebService中使用的List<string>类型的方法参数,在客户端代理中需要使用string[]数组来做为参数值,传递给Webservice的代理方法,这些以后有空会单独再来讨论一下Webservice的参数类型问题。今天要分享的小经验有两个。

  首先,当我们需要动态的设置我们引用的webservice的URL时,该如何去做。例如,我们想将Webservice的Url配置在config配置文件中,或者在用户界面上让用户自己去输入这个Webservice的url时,我们该如何去做。

其实我们的Webservice提供了Url这个属性,我们可以在调用该Service时,直接给该Url属性赋值即可。我们需要做的就是在我们添加的Webservice引用上,点击右键-属性-然后将Webservice的URL Behavior属性设置为Dynamic即可。然后我们在客户端就可以如下来写了: 

LocalWebServiceProxy.StudentService service=new LocalWebServiceProxy.StudentService();
service.Url
=”http://211.13.23.56/StudentService.asmx”;
string userName=service.GetUserName();

         第二个和各位同学分享的就是,我们都知道Webservice是支持Session的,只要在WebMethod这个Attribute上添加一个参数EnableSession=true即可。如下:

 

代码
public class StudentService : System.Web.Services.WebService
{
[WebMethod(Description
="登录",EnableSession=true)]
public void Login(string userName,string pwd)
{
Context.Session[
"USER"]=userName;
}

[WebMethod(Description
="获取用户名",EnableSession=true)]
public string GetUserName()
{
if(Context.Session["USER"]!=null)
{
return Context.Session["USER"].ToString();
}
else
return string.Empty;
}
}

 

  但是我们动手实现过的同学都知道,即使这样,当在客户端调用Login方法后,客户端再次调用GetUserName方法时,发现Context.Session[“User”]仍然为空。我们可以通过如下方法进行解决,需要在客户端调用Webservice的代理类时,给予这个代理类实例赋上CookieContainer属性。如下:

 

代码
public class StudentServiceInstance
{
static LocalWebService.StudentService service;
public static LocalWebService.StudentService Service()
{
if (service == null)
{
service
= new LocalWebService.StudentService();
//这里可以动态的设置WebService的Url
//service.Url = "http://192.168.84.47/SchoolWebService";
service.CookieContainer = new System.Net.CookieContainer();
service.Credentials
= System.Net.CredentialCache.DefaultCredentials;
return service;
}
else
return service;
}
}

 

  上面的方法就是在客户端自定义一个用来实例化这个Webservice代理类实例的方法,该实例对象必须是静态对象,这样就保证了客户端在任何地方使用该自定义类来取得Webservice代理类对象时,都是同一个代理类对象。同时必须给实例化后的代理类对象设置CookieContainer属性和Credentials属性。

然后,我们在调用Webservice的地方可以如下: 

代码
protected void BtnGetUserName_Click(object sender, EventArgs e)
{
string userName = StudentServiceInstance.Service().GetUserName();

//如下调用时,Session不能共享
//LocalWebService.StudentService service = new SessionWebService.LocalWebService.StudentService();
//string userName = service.GetUserName();

ClientScriptManager cs
= this.ClientScript;
cs.RegisterClientScriptBlock(
this.GetType(), "info", "javascript:alert('"+userName+"')",true);
}
protected void BtnLogin_Click(object sender, EventArgs e)
{
StudentServiceInstance.Service().Login(
"school", "111111");

//如下调用时,Session不能共享
//LocalWebService.StudentService service = new SessionWebService.LocalWebService.StudentService();
//service.Login("school","111111");
}
原文地址:https://www.cnblogs.com/RascallySnake/p/1823036.html