如何在WEBSERVICE中提供身份验证的功能。我在CSDN上常看到当WEBSERVICE不允许匿名访问时如何解决的贴子。自己试了一下。其实这中间的难度不大,只要二三句代码就可以解决。
我这里建一个测试用的WEBSERVICE,里面没有写任何代码,只有建工程时的一个默认的方法HelloWorld(本来是注释的。我把它取消了).然后将此WEBSERVICE的匿名访问的选项取消,并将集成WINDOWS的选项也取消了。
建立一个WINFORM工程,我在这个工程里调用刚才的WEBSERVICE工程,在引用里添加一个WEB引用,这些和正常的步骤是一样的。下面其实我们只要修改一下刚才产生的代理类。在其构造函数里加上身份信息即可。
下面是开发工具自动生成的代理类。
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.2032
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
//
// 此源代码是由 Microsoft.VSDesigner 1.1.4322.2032 版自动生成。
//
namespace Test.localhost {
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Web.Services;
using System.Security;
using System.Net;
/// <remarks/>
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Service1Soap",Namespace="http://tempuri.org/")]
public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol {
/// <remarks/>
public Service1() {
this.Url = "http://localhost/WebServiceTest/Service1.asmx";
//这里是访问WEBSERVICE的身份信息。
NetworkCredential myCred = new NetworkCredential("Administrator","password","greystar.com");
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(this.Url),"Basic",myCred);//要求验证
this.Credentials=myCache;
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/HelloWorld",RequestNamespace="http://tempuri.org/",ResponseNamespace="http://tempuri.org/",Use=System.Web.Services.Description.SoapBindingUse.Literal,ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string HelloWorld() {
object[] results = this.Invoke("HelloWorld",new object[0]);
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginHelloWorld(System.AsyncCallback callback,object asyncState) {
return this.BeginInvoke("HelloWorld",new object[0],callback,asyncState);
}
/// <remarks/>
public string EndHelloWorld(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
}
}
//这里是访问WEBSERVICE的身份信息。
NetworkCredential myCred = new NetworkCredential("Administrator",myCred);//要求验证
this.Credentials=myCache;
此时重编译一下你可以试一下,是不是成功了。对于其他方式的WEB请求,如果要求身份验证,也可以使用上面的方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。