NoWar
NoWar

Reputation: 37632

How to call webmethod from different website

I have website A which is done in ASP.NET and it has in default.aspx

[System.Web.Services.WebMethod]
public string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

May we call that method somehow from another website B using C#?

Thank you!

Upvotes: 1

Views: 2848

Answers (2)

lucdm
lucdm

Reputation: 143

Yes of course, webapi is created intentionally to be called from inside the same website, another website, and from a whatever client (console, winform, wpf, mobile apps, and so on) using c# or another language. .Net framework has avalaible various classes for calling webapi ex. HttpWebRequest, HttpClient or external libraries ex. RestSharp.

Upvotes: 1

Zafar
Zafar

Reputation: 3434

May we call that method somehow from another website B using C#?

Yes, you can make REQUESTS to the endpoint using C#. Either GET or POST

Simple GET request

var endPoint = "http://domain.com/default.aspx";
var webReq = (HttpWebRequest)WebRequest.Create(endPoint);
using (var response = webReq.GetResponse()) {
    using (var responseStream = response.GetResponseStream()) {
        var reader = new StreamReader(responseStream);
        var responseString = reader.ReadToEnd();
        //Do whatever with responseString
    }
}

Simple POST request

var endPoint = "http://domain.com/default.aspx"
var data = "param1=hello&param2=world"
var webReq = (HttpWebRequest)WebRequest.Create(endPoint);
webReq.Method = "POST";
var bytes = Encoding.UTF8.GetBytes(data);
webReq.ContentLength = bytes.Length;
webReq.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = webReq.GetRequestStream()) {
    requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = webReq.GetResponse()) {
    using (var responseStream = response.GetResponseStream()) {
        var reader = new StreamReader(responseStream);
        var responseString = reader.ReadToEnd();
        //Do whatever with responseString
    }
}

This is a simple way of doing it. More info at MSDN.

You can use WebClient or HttpClient on the other hand. You can find example in this post also.

Upvotes: 2

Related Questions