1

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!

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • Yes, you can. it is a web service. – Matt Aug 17 '14 at 14:59
  • @Matt Thank you! Would you mind to provide an example of the code to do it, please? Is it possible to call it using WinForm app as well? – NoWar Aug 17 '14 at 15:01
  • This provides an example with jQuery: https://trentgardner.net/net/asp-net-webmethods-with-jquery-and-ajax/ – Matt Aug 17 '14 at 15:06
  • @Matt I mean can we call that method from C# code of other website? I mean to use WebClient of other approach.. – NoWar Aug 17 '14 at 15:07
  • @Matt Also, _"different web site"_ - so that link using script [will not work](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). Hth. – EdSF Aug 17 '14 at 16:38

2 Answers2

2

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.

Community
  • 1
  • 1
Zafar
  • 3,394
  • 4
  • 28
  • 43
1

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.

lucdm
  • 93
  • 1
  • 8