Search code examples
c#asp.netwcfvisual-studio-2013

ASP.NET Form - How do I send form data to external WCF Service


I have a WCF Service on a separate project (part of an API). Completely decoupled from my website. I have created a form on my ASP.NET site (started with an empty site, in Visual Studio 2013).

What is the approach to.

  1. Read/collect the values of the form when the submit button is clicked.
  2. Connect to the remote WCF Service to post the data to it.
  3. Receive the response from that WCF Service?

I see a lot of examples online, but in those examples everything is always in a single project and I am not sure what belongs where.

Ideally I would like to do this without jQuery/AJAX initially, and consider using those later.


Solution

  • In my opinion, you could add the service reference to the project by right-click the Project>Reference so that you could call the service method with the client proxy class. While if the service invocation pass through the HTTP, you can send a post/get request to the service endpoint with the HttpClient/Webclient/HttpWebRequest class. Just like the below code.

    Entity.

     [DataContract]
    public class BookInfo
    {
        [DataMember]
        public string Name { get; set; }
    }
    

    Method.

    static void Main(string[] args)
        {
            BookInfo bookInfo = new BookInfo()
            {
                Name = "Apple"
            };
            Console.WriteLine(callService(bookInfo));
        }
        private static string callService(BookInfo input)
        {
            string serviceUrl = "http://localhost:90/Service1.svc/booking";
            string stringPayload = "{\"bookInfo\":" + JsonConvert.SerializeObject(input) + "}";
            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            string rtn = client.UploadString(serviceUrl, "POST",stringPayload);
            return rtn;
        }
    

    HttpClient is more concise and easy to use,Here are some official document.

    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?redirectedfrom=MSDN&view=netframework-4.7.2