.NET core 搭建一个跨平台的 Web Service

以前搭建的webservice 都是基于.NET fromwork的,我们知道.NET fromwork是非跨平台的,只能部署在iis上,今天教大家用.NET core搭建一个可跨平台的Web Service

新建一个.net core空项目

给项目起一个名字

选一个.net框架,我这里选择的是 .NET 5,也可以选择.NET 6 7... 都是一样的

.NET 5会生成一个Startup类,.NET 6以上版本已经把Startup类取消了,直接把相关服务写在Program里面就行

依赖项 添加 NuGet程序包,搜索 soapcore 安装

在Service文件夹下添加一个接口和一个实现类

IContract:

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

namespace WebServiceDemo.Service.Interface
{
    [ServiceContract]
    interface IDemoService
    {
        [OperationContract]
        int Add(string a, string b);
    }
}

DemoService:

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebServiceDemo.Service.Interface;

namespace WebServiceDemo.Service
{
    public class DemoService : IDemoService
    {
        public int Add(string a, string b)
        {
            return Convert.ToInt32(a) + Convert.ToInt32(b);
        }
    }
}

Startup下添加如下代码,注入刚才的类作为单例服务模式,同时添加soapcore服务

cs 复制代码
public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddSingleton<IDemoService, DemoService>();
            services.AddSoapCore();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });

                endpoints.UseSoapEndpoint<IDemoService>("/Service.asmx", new SoapEncoderOptions(),
        SoapSerializer.DataContractSerializer);
            });
        }

启动项目,可以看到已经成功运行了webservice

用postman测试一下,测试成功!

打包发布到服务器

右键 》发布》 选择文件夹

将发布好的文件全部拷贝到对应服务器下

windows服务器的话运行WebServiceDemo.exe就行,linux的话运行WebServiceDemo.dll文件

或者指定端口号运行:

相关推荐
猹叉叉(学习版)2 天前
【ASP.NET CORE】 14. RabbitMQ、洋葱架构
笔记·后端·架构·c#·rabbitmq·asp.net·.netcore
Murphy20233 天前
.NetCore项目使用EF Core操作SQL Server
.netcore
码界奇点3 天前
基于.NET Core的CMS内容管理系统设计与实现
c++·毕业设计·.netcore·源代码管理
猹叉叉(学习版)4 天前
【ASP.NET CORE】 13. DDD初步实现
笔记·后端·架构·c#·asp.net·.netcore
武藤一雄4 天前
WPF Command 设计思想与实现剖析
windows·微软·c#·.net·wpf·.netcore
武藤一雄4 天前
WPF 资源解析:StaticResource & DynamicResource 实战指南
微软·c#·.net·wpf·.netcore
武藤一雄4 天前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
吹牛不交税4 天前
vue3项目部署到阿里云Alibaba Cloud Linux3系统的docker
docker·容器·.netcore
猹叉叉(学习版)5 天前
【ASP.NET CORE】 12. DDD基本概念
笔记·后端·架构·c#·asp.net·.netcore
江沉晚呤时5 天前
C# 接口默认实现与依赖注入实战指南:.NET 9 企业级开发高级技巧
c#·log4j·.net·.netcore