使用VS2019创建WebService

Brh*_*aka 3 .net c# web-services visual-studio visual-studio-2019

我想使用 Visual Studio 2019 在现有的 .NET 项目中创建一个 WebService,使用 C#。在互联网上搜索,我能找到的只是旧版 VS 版本的教程......


如何创建它,使用 Visual Studio 2019 接收 POST 数据的最佳方法是什么?

Brh*_*aka 10

考虑到您已打开解决方案:

  • 右键单击项目名称(在解决方案资源管理器中),转到“添加”,然后选择“添加新项目...”

第一步

  • 选择“Visual C#”,向下滚动,选择“Web Service (ASMX)”,然后单击“添加”

第二步

在项目的根文件夹中创建了一个名为WebService.asmx(或您输入的名称)的文件。在里面,您应该看到该代码:

<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
Run Code Online (Sandbox Code Playgroud)

此文件仅用于调用代码,位于"~/App_Code/WebService.cs"。所以如果你想从POST / GET调用它,你应该使用:

www.host.com/pathTo/projectRoot/WebService.asmx/functionName?Params=values

打开"~/App_Code/WebService.cs" 后,您应该会看到如下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,您可以自定义代码以接收和处理POST / GET数据。

请注意Request["param"],您应该使用HttpContext.Current.Request["param"];.

  • @PanagiotisKanavos 以及说“它们有完整的文档记录”,实际链接到相关文档会更有用。如果我对此完全陌生(并且有人在网上搜索术语可能会找到这个答案)我如何知道有哪些文档以及在哪里?例如,我刚刚尝试搜索 VS2019 帮助,但它没有这个答案有用。显然我正在寻找“错误的东西” - 但我应该寻找什么? (3认同)
  • @ĴošħWilliard,只要答案没有错误。不过这个答案是错误的 - 是的,已经有很多文档了,不,您没有使用 ASMX 模板创建 SOAP 服务 (2认同)
  • ASMX 不是最推荐的,因为它很旧,但我用来集成数千个寄存器,没有问题。 (2认同)
  • @RyanWilson 在当今时代,答案将是 ASP.NET Core GRPC :P (2认同)
  • 由于价格、兼容性甚至偏好,@PanagiotisKanavos 使用旧的和过时的 API、软件等确实很常见。 (2认同)
  • 我希望这是最新的。 (2认同)
  • 如果缺少“WebService.asmx”模板或 ASP.NET Web 应用程序项目模板,请使用 Visual Studio 安装程序并添加“asp.net 和 Web 工具”组件 (2认同)

小智 6

这就是我创建带有 asmx 页面的项目的方式。 创建新项目

创建一个空的

右键单击一个新项目

并查找 webservice.asmx