简体   繁体   中英

How to access a WCF REST Service inside .Net web application?

I have a WCF web service which returns a JSON string from a Silverlight appication. I want to parse this JSON string inside a controller method in another web application. I cant create a service reference to the WCF service I created in Silverlight in the web application since it is a REST service. How can I access this WCF REST service in the other application?

You should use something like the System.Net.WebRequest to call the WCF service in your controller.

There are a plethora of examples online on how to use it properly.

Personally, I use JSON.Net or AngularJS in all of my applications.

I was able to access the web service with the following code

using System.Net;

public string GetWebServiceData()
    {
        try
        {
            string requestUrl = "requesturl";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "application/json";
            request.ContentLength = 0;
            request.Expect = "application/json";
            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string json = reader.ReadToEnd();
            return json;
        }
        catch (Exception)
        {
            return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(string.Empty);
        }

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM