如何为 WebService1.asmx 添加 [WebMethod] 文件?

我在 C# 中有一个服务器端项目。 我正在连接到 SQL Server 并希望将它的参数传递给一个表。

如何打开 WebMethod 文件?我在任何地方都找不到 既不是 WebService 项目。

如何为 WebService1.asmx 添加 [WebMethod] 文件?

附注
我读到 WebService asmx 已过时,但通过使用 ASP.NET Core Web API 项目,我将无法在 Chrome 浏览器中将参数从服务器端传递给 SQL。

先谢谢了。

zhengshinanhai 回答:如何为 WebService1.asmx 添加 [WebMethod] 文件?

我想你可能有点困惑; [WebMethod] 不是文件类型,它是您应用于服务中的方法以将它们标记为可用于远程调用的属性。将属性添加到方法后,它将出现在服务的 Web 服务定义中导出的方法列表中

using System;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService
{
    public Service ()
    {

    }


    [WebMethod]
    public string GetTime()
    {
        return DateTime.Now.ToString("HH:mm:ss");
    }

    public string GetDate()
    {
        return DateTime.Today.ToString("yyyy-MM-dd");
    }
}

如果你运行这个,你会看到:

enter image description here

GetTime,但没有 GetDate,因为 GetDate 未标记为网络方法

ASMX 已经很老了 - 它很简单,但是很老了.. 现在越来越少有人创建基于 XML 的网络服务(唉),但如果他们这样做,他们可能会使用 WCF,而不是 ASMX

我建议您切换到 netcore API;模板开箱即用——我认为你会得到一个天气预报——你可以创建一个新项目,点击播放,它就可以工作了。您可以使用例如与它进行交互邮递员或失眠。您可以添加新操作,它确实支持对 SQL 的参数化查询,您不需要 EF ..而且它将基于 JSON,这几乎是现代 Web 的发展方向

,

我通过打开一个新项目解决了这个问题:ASP.NET Empty Web Site
我添加了一个新项目作为“Web 服务 (ASMX)”,它在 WebService.asmx 文件夹中创建了一个 WebService.cs 文件和一个 App_Code 文件。

我之前在这个问题中打开的 ASP.NET Web Application 已在我添加的 ASMX 文件中的 WebMethod 中构建,
如我此处所示 -

WebService1.asmx

Public Class WebService1
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

End Class

我不熟悉如何在其中实现 webMethods 的约定。
如果您知道如何以这种方式书写 <WebMethod()> _,我将不胜感激 :)

谢谢

本文链接:https://www.f2er.com/1347.html

大家都在问