0
Silverlight에서 webhttpbinding을 사용할 수 없기 때문에 서비스 참조를 내 REST wcf 서비스에 추가 할 수 없으며 Visual Studio를 통해 프록시 클래스를 생성 할 수 없으므로 own, 나는 WebClient와 같은 것을 사용하여 Silverlight에서 사용할 비동기 REST Proxy 클래스를 어떻게 만들 수 있습니까?webHttpBinding JSON 웹 서비스 용 비동기 프록시 클래스 만들기
다음은 프록시 클래스를 구현 한 일부 코드입니다. 올바른 코딩 방식입니까?
public class RestProxy
{
private const string REST_URL = "http://.../RestService.svc";
private delegate int AddDelegate(int num1, int num2);
private delegate void AddCompleted(int result);
public AddCompleted AddOnCompleted { get; set;}
public int Add(int num1, int num2)
{
const string rest_method = "/Add";
//create json serializer.
JavaScriptSerializer serializer = new JavaScriptSerializer();
//add parameters to send into dictionary.
Dictionary<string, string> numberData = new Dictionary<string, string>();
postData.add("number1", num1.toString());
postData.add("number2", num2.toString());
//serialize dictionary to json.
string jsonData = serializer.Serialize(numberData);
//make request
string responseData = MakeRequest(REST_URL + rest_method, jsonData);
//deserialize json response data to dictionary.
Dictionary<string, string> numberResult = (Dictionary<string,string>)serializer.Deserialize(responseData, typeof(Dictionary<string,string>));
return Convert.toInt32(numberResult["AddResult"]);
}
public void AddAsync(int num1, int num2)
{
AddDelegate addAsync = new AddDelegate(this.Add);
addAsync.BeginInvoke(int num1, int num2, (IAsyncResult async_result) => {
//get caller
AsyncResult result = (AsyncResult)async_result;
AddDelegate caller = (AddDelegate)result.AsyncDelegate;
//get result.
int resultNumber = caller.EndInvoke(result);
//call callback delegates.
if(AddOnCompleted != null) AddOnCompleted(resultNumber);
}, null);
}
protected string MakeRequest(string address, string data_to_send)
{
WebClient webclient = new WebClient();
byte[] responseBytes = webclient.UploadData(new Uri(address), "POST", Encoding.ASCII.GetBytes(data_to_send));
return Encoding.ASCII.GetString(responseBytes);
}
public static void Main(string[] args)
{
RestProxy proxy = new RestProxy();
proxy.AddOnCompleted += new AddOnCompleted((int result) => { Console.WriteLine(result)});
proxy.AddAsync(10, 10);
}
}
덕분에 리처드는, 그러나 내가하고 싶은 예를 들어
여기 내가 사용하는 간단한 래퍼 클래스입니다 (URL이 정적 문자열 속성입니다) 제 3 자 라이브러리를 사용하지 않고 프록시 클래스를 직접 코딩하십시오. – rjs