如何在 .Net Web 应用程序中访问 WCF REST 服务?
How to access a WCF REST Service inside .Net web application?
我有一个 WCF Web 服务,其中 returns 来自 Silverlight 应用程序的 JSON 字符串。我想在另一个 Web 应用程序的控制器方法中解析此 JSON 字符串。我无法在 Web 应用程序中创建对我在 Silverlight 中创建的 WCF 服务的服务引用,因为它是 REST 服务。如何在其他应用程序中访问此 WCF REST 服务?
您应该使用类似 System.Net.WebRequest 的方式在您的控制器中调用 WCF 服务。
网上有大量关于如何正确使用它的示例。
我能够使用以下代码访问网络服务
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);
}
}
}
我有一个 WCF Web 服务,其中 returns 来自 Silverlight 应用程序的 JSON 字符串。我想在另一个 Web 应用程序的控制器方法中解析此 JSON 字符串。我无法在 Web 应用程序中创建对我在 Silverlight 中创建的 WCF 服务的服务引用,因为它是 REST 服务。如何在其他应用程序中访问此 WCF REST 服务?
您应该使用类似 System.Net.WebRequest 的方式在您的控制器中调用 WCF 服务。
网上有大量关于如何正确使用它的示例。
我能够使用以下代码访问网络服务
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);
}
}
}