.NET WebService \ WCF \ WebAPI 部署总结 以及 window 服务 调试

一、webservice 部署只能部署IIS上,

比较简单,就不做说明了

二、 WCF 部署 1

部署到IIS 跟部署 webservice 部署方法一样的

wcf 部署2

部署到控制台 要以管理员运行vs,或者 管理员运行 控制台的exe

在控制器项目中

创建IUserInfoService 接口

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    [ServiceContract]
    public interface  IUserInfoService
    {
        [OperationContract]
        int Add(int a, int b);
    }
}

实现接口

在app.config中增加

csharp 复制代码
 <system.serviceModel>
    <services>

      <service name="ConsoleApp1.UserInfoService" behaviorConfiguration="behaviorConfiguration">
        <!--服务的对象-->
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/"/>
            <!--服务的IP和端口号-->
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="ConsoleApp1.IUserInfoService"></endpoint>
        <!--contract:服务契约-->
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="behaviorConfiguration">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

《《《启动服务

》》》验证是否有效

》》》如果不放在配置文件中

》》》

csharp 复制代码
 using (ServiceHost host = new ServiceHost(typeof(UserInfoService)))
            {
                host.AddServiceEndpoint(typeof(IUserInfoService), new WSHttpBinding(), "http://localhost:8686/userinfoservice");
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                behavior.HttpGetUrl = new Uri("http://localhost:8686/userinfoservice/metadata");
                host.Description.Behaviors.Add(behavior);
                host.Opened +=delegate
                { 
                    Console.WriteLine("服务已启动");
                };
                host.Open();             
                Console.ReadKey();
                host.Close();
            }

》》》 校验是否成功


部署到winform

csharp 复制代码
 private void button1_Click(object sender, EventArgs e)
        {
            ServiceHost Host = new ServiceHost(typeof(WCF.Student));
            

                //绑定
                System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();
                //终结点
                Host.AddServiceEndpoint(typeof(IWCF.IStudent), httpBinding, "http://localhost:8002/");
                if (Host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    //行为
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;

                    //元数据地址
                    behavior.HttpGetUrl = new Uri("http://localhost:8002");
                    Host.Description.Behaviors.Add(behavior);

                    //启动
                    Host.Open();

                
            }
        }

》》》验证

app.config 配置

csharp 复制代码
      <service name="WCF.Student" behaviorConfiguration="behaviorConfiguration">
        <!--//服务的对象-->
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:5678"/>
           <!--// 服务的IP和端口号-->
          </baseAddresses>
        </host>
        <endpoint address="" binding="wsHttpBinding" contract="IWCF.IStudent"></endpoint>
        <!--//contract:服务契约-->
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="behaviorConfiguration">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

》》》》验证

WCF 宿主 服务中


》》》 app.config 或者写作code 都行


LocalService:充当本地计算机上非特权用户的帐户,该帐户将匿名凭据提供给所有远程服务器。

NetworkService:提供广泛的本地特权的帐户,该帐户将计算机的凭据提供给所有远程服务器。

LocalSystem:服务控制管理员使用的帐户,它具有本地计算机上的许多权限并作为网络上的计算机。

User:由网络上特定的用户定义的帐户。如果为 ServiceProcessInstaller.Account 成员指定 User,则会使系统在安装服务时提示输入有效的用户名和密码,除非您为 ServiceProcessInstaller 实例的 Username 和 Password 这两个属性设置值。



删除服务

sc delete 服务名称

window 服务调试

正常是无法调试的,可以在window服务中做调整

如下




window 服务 卸载

》》》1 在cmd中 录入 sc delete 服务名称 注意注意 是服务名称 不是显示名称

这种方法 不需要 停车服务,可以直接干掉

》》》2、 代码实现

卸载前,一定要停止掉Windows服务,否则需要重启或注销电脑。代码无法停止服务时,使用services.msc来停止。

获取系统所有window 服务

ServiceController[] services = ServiceController.GetServices();

》》》》"Service1.cs"的代码,增加服务启动日志和停止日志。

csharp 复制代码
using CommonUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace ADemoWinSvc
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            GLog.WLog("服务已启动");
        }

        protected override void OnStop()
        {
            GLog.WLog("服务已停止");
        }
    }
}

》》》》 工具类

csharp 复制代码
using System;
using System.IO;

namespace CommonUtils
{
     
    public static class GLog
    {
        static object _lockObj = new object();

        public static void WLog(string content)
        {
            lock (_lockObj)
            {
                string curPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                string logDir = "Logs";
                string logDirFullName = Path.Combine(curPath, logDir);

                try
                {
                    if (!Directory.Exists(logDirFullName))
                        Directory.CreateDirectory(logDirFullName);
                }
                catch { return; }

                string fileName = "Logs" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                string logFullName = Path.Combine(logDirFullName, fileName);

                try
                {
                    using (FileStream fs = new FileStream(logFullName, FileMode.Append, FileAccess.Write))
                    using (StreamWriter sw = new StreamWriter(fs))
                        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + content);
                }
                catch { return; }

            }
        }
    }
}

========= 上面代码都是 服务中的

下面代码 是winForm程序中的==

csharp 复制代码
using CommonUtils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Windows服务操作
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// windows服务名
        /// </summary>
        static string _winSvcName = "ADemoWinSvc";

        /// <summary>
        /// windows服务对应的exe 名
        /// </summary>
        static string _winSvcExeName = "ADemoWinSvc.exe";

        private void btnSetup_Click(object sender, EventArgs e)
        {
            try
            {
                //是否存在服务
                if (ServiceUtil.ServiceIsExisted(_winSvcName))
                {
                    //已存在,检查是否启动
                    if (ServiceUtil.IsRun(_winSvcName))
                    {
                        //服务是已启动状态
                        lblMsg.Text = "[001]服务是已启动状态";
                    }
                    else
                    {
                        //未启动,则启动
                        ServiceUtil.StarService(_winSvcName);
                        lblMsg.Text = "[002]服务是已启动状态";
                    }
                }
                else
                {
                    //不存在,则安装
                    IDictionary mySavedState = new Hashtable();
                    string curPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                    string apppath = Path.Combine(curPath, _winSvcExeName);
                    ServiceUtil.InstallService(mySavedState, apppath);

                    lblMsg.Text = "[003]服务是已启动状态";

                    //安装后并不会自动启动。需要启动这个服务
                    ServiceUtil.StarService(_winSvcName);

                    lblMsg.Text = "[004]服务是已启动状态";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnUninstall_Click(object sender, EventArgs e)
        {
            //** 卸载服务最重要的是先停止,否则电脑需要重启或注销 **
            try
            {
                //是否存在服务
                if (!ServiceUtil.ServiceIsExisted(_winSvcName))
                {
                    MessageBox.Show("服务不存在,不需要卸载");
                    return;
                }

                //如果服务正在运行,停止它
                if (ServiceUtil.IsRun(_winSvcName))
                {
                    ServiceUtil.StopService(_winSvcName);
                }
                //再检查一次是否在运行
                if (ServiceUtil.IsRun(_winSvcName))
                {
                    MessageBox.Show("服务无法停止,请手动停止这个服务");
                    return;
                }
                //卸载
                ServiceUtil.UnInstallServiceByName(_winSvcName);

                lblMsg.Text = "[005]服务已卸载";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

》》》》》

AssemblyInstaller 帮助文件

https://learn.microsoft.com/zh-cn/dotnet/api/system.configuration.install.assemblyinstaller?view=netframework-4.8.1

》》》》 工具类

csharp 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace CommonUtils
{
    /// <summary>
    /// windows服务操作工具类
    /// </summary>
    public static class ServiceUtil
    {
        /// <summary>
        /// 服务是否正在运行
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool IsRun(string name)
        {
            bool IsRun = false;
            try
            {
                if (!ServiceIsExisted(name)) return false;
                var sc = new ServiceController(name);
                if (sc.Status == ServiceControllerStatus.StartPending || sc.Status == ServiceControllerStatus.Running)
                {
                    IsRun = true;
                }
                sc.Close();
            }
            catch
            {
                IsRun = false;
            }
            return IsRun;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool StarService(string name)
        {
            try
            {
                var sc = new ServiceController(name);
                if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus.StopPending)
                {
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
                }
                else
                {

                }
                sc.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 停止服务(有可能超时)
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool StopService(string name)
        {
            try
            {
                var sc = new ServiceController(name);
                if (sc.Status == ServiceControllerStatus.Running || sc.Status == ServiceControllerStatus.StartPending)
                {
                    sc.Stop();
                    //停止服务超时时间:56秒。
                    sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 56));
                }
                else
                {

                }
                sc.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
                if (s.ServiceName.ToLower() == serviceName.ToLower())
                    return true;
            return false;
        }

        /// <summary>
        /// 安装
        /// </summary>
        /// <param name="stateSaver"></param>
        /// <param name="filepath"></param>
        public static void InstallService(IDictionary stateSaver, string filepath)
        {
            try
            {
                AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
                myAssemblyInstaller.UseNewContext = true;
                myAssemblyInstaller.Path = filepath;
                myAssemblyInstaller.Install(stateSaver);
                myAssemblyInstaller.Commit(stateSaver);
                myAssemblyInstaller.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 使用路径卸载(有时候不便于用路径来卸载,则使用SC DELETE 名称来卸载)
        /// </summary>
        /// <param name="filepath"></param>
        public static void UnInstallService(string filepath)
        {
            try
            {
                AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
                myAssemblyInstaller.UseNewContext = true;
                myAssemblyInstaller.Path = filepath;
                myAssemblyInstaller.Uninstall(null);
                myAssemblyInstaller.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 使用windows服务名卸载
        /// </summary>
        /// <param name="WinServiceName"></param>
        public static void UnInstallServiceByName(string WinServiceName)
        {
            ProcessStartInfo pStart = new ProcessStartInfo("sc.exe");
            Process pRoc = new Process();

            pStart.Arguments = " delete " + WinServiceName;
            pStart.UseShellExecute = false;
            pStart.CreateNoWindow = false;

            pRoc.StartInfo = pStart;
            pRoc.Start();
            pRoc.WaitForExit();
        }





        

    }
}

WebAPI 部署

部署 IIS

跟wcf 、webservice 一样。

部署 控制台
相关推荐
WineMonk3 小时前
.NET WPF CommunityToolkit.Mvvm框架
.net·wpf·mvvm
界面开发小八哥3 小时前
界面控件DevExpress WPF中文教程:Data Grid——卡片视图设置
.net·wpf·界面控件·devexpress·ui开发
九鼎科技-Leo14 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo17 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
.net开发17 小时前
WPF怎么通过RestSharp向后端发请求
前端·c#·.net·wpf
九鼎科技-Leo21 小时前
在 C# 中,ICollection 和 IList 接口有什么区别?
windows·c#·.net
时光追逐者21 小时前
C#/.NET/.NET Core学习路线集合,学习不迷路!
开发语言·学习·c#·asp.net·.net·.netcore·微软技术
Crazy Struggle1 天前
.NET 全功能流媒体管理控制接口平台
.net·开源项目·流媒体
.net开发1 天前
WPF使用prism框架发布订阅实现消息提示
c#·.net·wpf