c# - 从 Web 服务实例化对象与从常规类实例化对象

标签 c# asp.net webrequest

我有一个非常基本的网络服务:

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

namespace WebService1
{        
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [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
    {

        public int myInt = 0;

        [WebMethod]
        public int increaseCounter()
        {
            myInt++;
            return myInt;
        }

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

    }
}

当我运行该项目时,我的浏览器打开并向我显示该服务: enter image description here


在不同的解决方案上:(控制台应用程序)

我可以通过添加引用来连接到该服务:

enter image description here

enter image description here

然后点击添加网络引用按钮: enter image description here

最后,我输入刚刚创建的服务的 url: enter image description here

现在我可以从我的控制台应用程序中实例化一个类 Service1 的对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication36
{
    class Program
    {
        static void Main(string[] args)
        {
            localhost.Service1 service = new localhost.Service1();

            // here is the part I don't understand..
            // from a regular class you will expect myInt to increase every time you call
            // the increseCounter method. Even if I call it twice I always get the same result.

            int i;
            i=service.increaseCounter();
            i=service.increaseCounter();


            Console.WriteLine(service.increaseCounter().ToString());
            Console.Read();


        }
    }
}

为什么我每次调用 increaseCounter 方法时 myInt 都不增加?每次我调用该方法时,它都会返回 1。

最佳答案

通过旧的 .asmx 技术创建的服务不是单例实例。这意味着每次调用服务器都会实例化一个新的服务实例。两个真正的解决方案,要么使用静态变量(呃....),要么改用 WCF。

关于c# - 从 Web 服务实例化对象与从常规类实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589301/

相关文章:

asp.net - Docker 从一个容器复制到另一个容器

c# - 在c#中多线程处理大量的web请求

.net - 使用 webrequest 时如何保持连接?

php - 在 PHP 中获取唯一的 worker/thread/process/request ID

c# - 传递给 MVC Controller 的 id 总是映射为 0

c# - 捕获失败的授权策略

c# - 无法让 SAFEARRAY 与 Interop 一起工作

c# - Winforms UI 无响应查询

javascript - ASP.Net 和 AngularJS 路由错误 : Tried to load angular more than once

c# - 如何不允许用户在文本框中输入数字