测试ASP.NET Core的WebApi项目调用WebService

虚拟机中部署的匿名访问的WebService,支持简单的加减乘除操作。本文记录在WebApi中调用该WebService的方式。

  VS2022创建WebApi项目,然后在解决方案资源管理器的Connected Services节点点右键,选择管理连接的服务菜单。

点击下图圈红处的加号按钮。


  在弹出的添加服务引用窗口中选择"WCF Web Service",然后点击下一步按钮。

在下图URI输入框中输入WebService地址(如果是本地wsdl文件,则输入wsdl文件地址或点击浏览按钮选择文件),然后点击转到按钮查看WebService支持的函数。按需在最下方修改WebService命名空间,然后点击下一步按钮。

根据项目需要设置数据类型选项及客户端选项(如下面几张截图所示),然后点击完成按钮创建服务引用。



WebService添加后,会在解决方案资源管理器的项目下增加Connected Services文件夹,在其下即可查看生成的服务代码。

  采用参考文献1中介绍的第2种方法在WebApi中调用WebService,由于是匿名访问,采用默认设置即可。主要代码如下所示:

csharp 复制代码
public class MathOptController : ControllerBase
{
    private MathServiceSoapClient m_client = null;
    public MathOptController()
    {
        BasicHttpBinding binding = new BasicHttpBinding();

        EndpointAddress address = new EndpointAddress("http://192.168.11.50:8088/MathService.asmx");

        m_client = new MathServiceSoapClient(binding, address);
    }

    [HttpGet]
    public int Add(int a,int b)
    {
        Task<int> result= m_client.AddAsync(a,b);
        return result.Result;
    }
}

最后是运行效果截图。


参考文献:

1\]https://www.cnblogs.com/songjuntao/p/15327698.html \[2\]https://blog.csdn.net/emirma/article/details/128239616

相关推荐
Murphy20232 天前
.net8 Swashbuckle.AspNetCore WEBAPI 配置要点记录
.net·swagger·webapi·swashbuckle
.NET修仙日记2 天前
Acme.ReturnOh:让.NET API返回值处理更优雅,统一响应格式一步到位
c#·.net·webapi
ChaITSimpleLove6 天前
aiagent-webapi 命令的详细使用说明
dotnet·webapi·ai agent·agent framework·maf·projecttemp
lujunql10 天前
CMake 生成Visual Studio 2022工程---第三章.Eclipse Paho C
mqtt·vs2022·eclipse paho c
lujunql11 天前
CMake 生成Visual Studio 2022工程---第四章.Eclipse Paho MQTT CPP
mqtt·vs2022·eclipsepahocpp
wstcl2 个月前
像asp.net core webapi一样在asp.net frameworks中使用Swagger,方便调试接口
后端·asp.net·swagger·webapi
xiaoid3 个月前
C#向jave平台的API接口推送
c#·post·webapi
lpruoyu4 个月前
WebService — apache axis 1.4 — wsdl — 整合第三方短信
webservice·wsdl·axis
csdn_aspnet4 个月前
使用 .NET 8 构建 RESTful Web API
restful·webapi·.net8
csdn_aspnet4 个月前
在 .Net 8 WEBAPI 中实现实体框架的 Code First 方法
webapi·.net8