Home > Software design >  How to add a [WebMethod] file for WebService1.asmx?
How to add a [WebMethod] file for WebService1.asmx?

Time:09-17

I have a project with server side in C#. I'm connecting to the SQL Server and want to pass it parameters to a table.

How do I open a WebMethod file ? I can't find it anywhere neither a WebService project.

enter image description here

P.S
I read that WebService asmx is obsolete, but by using a ASP.NET Core Web API project I will not be able to pass parameters to SQL from the server side in the Chrome browser.

Thanks is advance.

CodePudding user response:

I think you might be slightly confused; [WebMethod] isn't a type of file, it's an attribute you apply to methods in your service to mark them as available for calling remotely. Once you've added the attribute to a method, it will appear in the list of methods exported in the service's webservice definition

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");
    }
}

If you ran this you'd see:

enter image description here

GetTime, but no GetDate, because GetDate isn't marked as a webmethod

ASMX is very old - it's simple, but very old.. It's increasingly rare to even find people creating XML based webservices (alas) these days, but if they do they probably use WCF, not ASMX

I would recommend you switch to netcore API; the templates work out of the box - you get a Weather Forecast one I think - you can just create a new project, hit play and it works. You can interact with it using e.g. Postman or Insomnia. You can add new operations, it does support parameterized queries to SQL, you don't need EF.. And it'll be JSON based, which is pretty much the direction the modern web has gone in

CodePudding user response:

I solved this problem by opening a new project as: ASP.NET Empty Web Site.
I added it a new item as "Web Service (ASMX)" which created a WebService.asmx file and also a WebService.cs file inside a App_Code folder.

The ASP.NET Web Application I opened before in this question had build in a WebMethod inside ASMX file I added,
as I shown here -

WebService1.asmx

Public Class WebService1
Inherits System.Web.Services.WebService

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

End Class

Which I'm not familiar with this convention of how to implement webMethods in it.
If you know how to write <WebMethod()> _ this way I'll be grateful for your answer :)

Thanks

  • Related