.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文件

或者指定端口号运行:

相关推荐
deriva4 天前
.netcore+ef+redis+rabbitmq+dotcap先同步后异步再同步的方法,亲测有效
redis·rabbitmq·.netcore
棉晗榜20 天前
C# .net core添加单元测试项目,依赖注入接口测试
单元测试·c#·.netcore
时光追逐者20 天前
.NET初级软件工程师面试经验分享
经验分享·面试·职场和发展·c#·.net·.netcore
忧郁的蛋~21 天前
.NET Core 实现缓存的预热的方式
缓存·c#·.net·.netcore
csdn_aspnet22 天前
C# .NET Core 源代码生成器(dotnet source generators)
c#·.netcore
时光追逐者22 天前
C#/.NET/.NET Core技术前沿周刊 | 第 42 期(2025年6.9-6.15)
c#·.net·.netcore
csdn_aspnet23 天前
使用 C# 源生成器(Source Generators)进行高效开发:增强 Blazor 及其他功能
c#·.netcore
lgaof65822@gmail.com25 天前
Asp.Net Core SignalR导入数据
前端·后端·asp.net·.netcore
眸笑丶25 天前
.NET Core 数据库连接字符串加密与解密
数据库·oracle·.netcore
时光追逐者1 个月前
C#/.NET/.NET Core技术前沿周刊 | 第 41 期(2025年6.1-6.8)
c#·.net·.netcore