如何从Web服务代码(C#)访问内部ASP.NET对象?

时间:2009-05-20 20:57:41

标签: c# asp.net web-services

具体来说,我需要针对数据库验证传入的X.509安全证书,以允许访问我的Web服务。为此,我需要获取客户端发送的证书的副本。我想我知道如何做到这一点,如果我能弄清楚如何访问http Request对象 - 一个内在的ASP.NET对象。

我找到了以下代码,该代码描述了如何创建将执行此操作的组件,以及如何在aspx页面上的Page Load事件的代码隐藏中加载它。这很好,我从文章中学到了很多,但它仍然没有解决我的问题 - 没有网页,所以没有页面加载事件。

如何:使用Visual C#.NET从.NET组件访问ASP.NET内部对象 http://support.microsoft.com/kb/810928

我使用的是C#和.NET 3.5,但我没有使用C#的高级编码功能(lambdas,扩展方法等)。我还没有花时间学习如何使用它们......

任何提示,指示,示例代码都将非常感激。 谢谢, 戴夫

1 个答案:

答案 0 :(得分:4)

如果它是asmx Web服务(即“page”/入口点是somefile.asmx,那么它应该像从那里访问请求对象一样简单。

实施例: 在Visual Studio中,创建Web服务应用程序,并将以下代码粘贴到service1.asmx.cs中:(以下示例返回Web请求中所有标头的名称)

(以下是service1.asmx.cs的完整内容)


using System;
using System.Web;
using System.Web.Services;

namespace WebServiceIntrinsicObjects
{
    /// 
    /// Summary description for Service1
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            // HERE'S THE LINE:  just get the request object from HTTPContext.Current (a static that returns the current HTTP context)
            string test = string.Join(",", HttpContext.Current.Request.Headers.AllKeys);
            return test;
        }
    }
}