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

或者指定端口号运行:

相关推荐
亦世凡华、1 天前
掌握.NET Core后端发布流程,如何部署后端应用?
经验分享·.netcore·docker部署·程序发布
contact972 天前
.NET Core中的五种过滤器详解
.netcore·过滤器
以为不会掉头发的詹同学2 天前
【 Avalonia UI 语言国际化 I18n】图文结合教学,保姆级教学,语言国际化就是这么简单(.Net C#)
开发语言·前端·c#·.netcore·用户界面
爱吃香蕉的阿豪4 天前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
shepherd枸杞泡茶4 天前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
.NET快速开发框架5 天前
使用nvm管理node.js版本,方便vue2,vue3开发
vue·.netcore·常用工具·开发技术·rdif
csdn_aspnet6 天前
ASP.NET Core 使用 FileStream 将 FileResult 文件发送到浏览器后删除该文件
asp.net·.netcore
csdn_aspnet6 天前
ASP.NET Core SixLabors.ImageSharp v1.0 的图像实用程序类 web示例
asp.net·.netcore
csdn_aspnet6 天前
ASP.NET Core SixLabors.ImageSharp 位图图像创建和下载
asp.net·.netcore
时光追逐者9 天前
C#/.NET/.NET Core技术前沿周刊 | 第 24 期(2025年1.27-1.31)
microsoft·c#·.net·.netcore·微软技术