ASP.NET AJAX 客户端 访问 Web Service(7)

本文介绍如何在ASP.NET WebService中利用Session进行数据存储与传递,并通过配置确保服务的安全性,包括使用FormsAuthentication进行身份验证,以及在特定场景下限制匿名访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在WebService方法中使用Session

  • ASP.NET中每个请求都由一个IHttpHandler对象来处理
  • 在处理时要使用Session则需要让Handler对象实现IRequiresSessionState借口
  • RestHandlerFactory根据所请求的方法的标记来选择是否启用Session
  • 启用方法:在WebMethodAttribute中标记(EnableSession属性设置为true)
一个在WebService方法中使用Session的示例

首先创建一个名为EnableSessionService.asmx的WebService

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

/// <summary>
///EnableSessionService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
[System.Web.Script.Services.ScriptService]
public class EnableSessionService : System.Web.Services.WebService
{
    [WebMethod(EnableSession = true)]
    public int AddOne()
    {
        object objValue = Session["value"];
        int value = objValue == null ? 0 : (int)objValue;
        value++;
        Session["value"] = value;
        return value;
    }

    [WebMethod(true)]
    public int AddTwo()
    {
        object objValue = Session["value"];
        int value = objValue == null ? 0 : (int)objValue;
        value += 2;
        Session["value"] = value;
        return value;
    }
}

然后创建一个页面使用它

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/Demo03/EnableSessionService.asmx" InlineScript="true" />
            </Services>
        </asp:ScriptManager>
        
        <input type="button" value="Add One" onclick="addOne()" />
        <input type="button" value="Add Two" onclick="addTwo()" />
        
        <script language="javascript" type="text/javascript">
            function addOne() {
                EnableSessionService.AddOne(onSucceeded);
            }

            function addTwo() {
                EnableSessionService.AddTwo(onSucceeded);
            }
            
            function onSucceeded(result) {
                alert(result);
            }
        </script>
    </form>
</body>
</html>

这样我们就可以正确的使用WebService访问Session啦,并且我们发现[WebMethod(EnableSession = true)]和[WebMethod(true)]的作用是一样的,区别就是,当我们需要设置一写其他属性的时候,我们就只能使用[WebMethod(EnableSession = true)]这种方式啦

 

安全性

  • 完全适用ASP.NET的认证机制(使用FormsAuthentication,Impersonation,PrincipalPermission)
  • ASP.NET AJAX访问WebService可以操作cookies
一个关于安全性的示例

首先,我们应该确定一下,web.config中的authentication标记的mode属性是否非Forms

创建一个名为SecurityService.asmx的WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
///SecurityService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
[System.Web.Script.Services.ScriptService]
public class SecurityService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            throw new ApplicationException("Please Login First");
        }
        return "Hello " + HttpContext.Current.User.Identity.Name;
    }
}

然后创建一个页面使用它

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/Demo03/SecurityService.asmx" InlineScript="true" />
            </Services>
        </asp:ScriptManager>
        
        <input type="button" value="Call" onclick="call()" />
        
        <script language="javascript" type="text/javascript">
            function call() {
                SecurityService.HelloWorld(onSucceeded,onFailed);
            }

            function onSucceeded(result) {
                alert(result);
            }

            function onFailed(error) {
                alert(error.get_message());
            }
        </script>
    </form>
</body>
</html>

这时,我们点击页面中的Call按钮,就会弹出一个Please login first,我们成功了阻止了一次匿名的登陆

我们在页面的Load事件中增加如下代码

FormsAuthentication.SetAuthCookie("Xiaoyaojian",false); 

这样,我们在页面加载的时候就为它登陆了,页面就会正常显示我们想要的内容:Hello ,Xiaoyaojian(注意要在页面代码中引入System.Web.Security命名空间)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值