如何在Web服务中传递数据?

时间:2012-10-31 23:28:45

标签: c# web-services

我想将数据用户ID和用户代码传递给另一台服务器并使用网络获取响应。

所以,我创建了这段代码

var webRequest = WebRequest.Create(@"http://10.2.1.85/");

工作正常,但我不知道如何传递用户ID和用户代码。
我是否必须创建对象?

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是如何在Web服务上发布数据:

WebService Post Function

public static string JsonPost(string url, string method, string postData)
{

    Uri address = new Uri(url + method);

    //Get User current network credential
    ICredentials credentials = CredentialCache.DefaultCredentials;
    NetworkCredential credential = credentials.GetCredential(address, "Basic");

    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
    request.Method = "POST";
    request.ContentType = "application/json";

    //Network Credential should be included on the request to avoid network issues when requesting to the web service
    request.Proxy = WebRequest.DefaultWebProxy;
    request.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
    request.Proxy.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);

    byte[] byteData = UTF8Encoding.UTF8.GetBytes(postData);
    request.ContentLength = byteData.Length;
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        StreamReader reader = new StreamReader(response.GetResponseStream());

        string JsonResponse = reader.ReadToEnd();

        return JsonResponse;
    }
}

登录功能

public static string Login(string Email, string Password)
{

    try
    {
        string postData = "{" + "\"Email\":\"" + Email + "\"," +
        "\"Password\":\"" + Password + "\"" +
        "}";

        string JsonResult = JsonPost("Your Web Service URL", "Login", postData);
        return JsonResult;
    }
    catch (Exception ex)
    {

        return "";
    }

}

示例如何使用:

public void LoginUser()
{
    string Email = "me@example.com";
    string Password = "password";
    string JsonUserAccount = Login(Email, Password);

    if(!string.IsNullOrEmpty(JsonUserAccount))
    {
        Debug.Print("User logged in");
    }
    else
    {
        Debug.Print("Failed to logged in");
    }

}