.net WebService方法之重载、支持Session、支持request请求和response格式的浅析

.net的webservice不支持web方法的重载,但是可以通过设置WebMethod属性的MessageName字段来达到重载web方法的目的。

通过设置WebMethod属性的EnableSession=true,可让webservice支持session。

通过设置ScriptMethod属性的UseHttpGet=false,可让web方法只接受post请求;如果UseHttpGet=true,可让web方法接受get请求。

通过设置ScriptMethod属性的ResponseFormat,可设置web方法响应的格式。如:ResponseFormat = ResponseFormat.Json。

上代码说明:

.net的webservice代码:

    [WebMethod(Description = "验证登录操作", EnableSession = true, MessageName = "Login")]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public Result Login(string userName, string pwd) {
        Result rc = null;

        try {
            if (userName == "1" && pwd == "1") {
                Session["User"] = new UserInfo { UserName = userName, pwd = pwd };
                rc = Result.ToResult("true", "登录成功");
            }
            else rc = Result.ToResult("false", "登录失败");
        }
        catch (Exception ex) {
            // 可以在此保存日志
            rc = Result.ToResult("false", ex.Message);
        }

        return rc;
    }

    [WebMethod(Description = "验证登录", EnableSession = true, MessageName = "IsLogin")]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public Result IsLogin() {
        Result rc = null;

        try {
            rc = Session["User"] != null ? Result.ToResult("true", "已经登录") : Result.ToResult("false", "暂未登录");
        }
        catch (Exception ex) {
            rc = Result.ToResult("false", ex.Message);
        }

        return rc;
    }

    public class Result {
        public string Code { get; set; }
        public string Message { get; set; }

        public static Result ToResult(string code, string message) {
            return new Result { Code = code, Message = message };
        }
    }

同站点下的html代码:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <script>
        function login() {
            var url = "http://localhost/wst/Service.asmx/Login";
            $.ajax({
                url: url,
                type: 'POST',
                data: '{"userName":"1","pwd":"1"}',//和WebService的web方法的参数一一对应
                dataType: 'json',
                cache:false,
                contentType: 'application/json',//                   
                error: function () { },
                success: function(data){
                    if (data.d != null) {
                        alert(data.d.Code+"  "+data.d.Message);
                    }
                    else alert("请求失败!");
                }
            });
        }

    </script>
</head>
<body>
    <input type="button" value="登录" onclick="login()"/>

</body>
</html>

用jQuery的ajax访问同源的webserver方法。

原文地址:https://www.cnblogs.com/williamwsj/p/7044877.html