使用VS2019创建WebService [英] Using VS2019 to create a WebService
问题描述
我想使用Visual Studio 2019在现有的.NET项目中使用C#创建一个WebService.搜索互联网,我所能找到的只是VS较旧版本的教程...
I want to use Visual Studio 2019 to create a WebService inside an existing .NET project, using C#. Searching the internet, all I could find were tutorials for older VS versions...
如何创建它?使用Visual Studio 2019接收POST数据的最佳方法是什么?
How can I create it, and what's the best approach for receiving POST data using Visual Studio 2019?
推荐答案
考虑打开解决方案:
- 右键单击项目名称(在解决方案资源管理器中),转到添加" ,然后转到添加新项目..."
- Right click on the project name (at the solution explorer), go to "Add" and than "Add new item..."
- 选择"Visual C#" ,向下滚动,选择"Web Service(ASMX)" ,然后单击添加" . >
- Select "Visual C#", scroll down, select "Web Service (ASMX)" and click "Add".
在项目的根文件夹上创建了一个名为 WebService.asmx 的文件(或您输入的名称).在内部,您应该看到该代码:
A file called WebService.asmx (Or the name you entered) was create on the root folder of your project. Inside, you should see that code:
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
此文件仅用于在〜/App_Code/WebService.cs" 处调用代码.因此,如果您想通过 POST 进行调用,则应使用
This file is just used to call the code, at "~/App_Code/WebService.cs". So if you want to call it from POST, you should use
www.host.com/pathTo/projectRoot/WebService.asmx/functionName?Params=values
打开〜/App_Code/WebService.cs" 后,您应该会看到类似的内容:
After opening "~/App_Code/WebService.cs", you should see something like that:
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";
}
}
在这里,您可以自定义代码以接收和处理 POST 数据.
Here, you can customize your code to receive and process POST data.
您不能在此处使用Request["param"]
,但是HttpContext.Current.Request["param"];
是我发现的最佳方法.
You can't use Request["param"]
here, but HttpContext.Current.Request["param"];
is the best approach I've found.
就像一个人所说的那样:ASMX是一种古老的实现方式,但是直到今天我们仍然有效.
这篇关于使用VS2019创建WebService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!