C# 如何在web服务中传递数据?
我想将数据用户Id和用户代码传递给另一台服务器,并使用网络获取响应 所以,我创建了这个代码C# 如何在web服务中传递数据?,c#,web-services,C#,Web Services,我想将数据用户Id和用户代码传递给另一台服务器,并使用网络获取响应 所以,我创建了这个代码 var webRequest = WebRequest.Create(@"http://10.2.1.85/"); 它工作正常,但我不知道如何传递用户Id和用户代码。 我必须创建对象还是什么 我该怎么做?这是如何在Web服务上发布数据: webservicepost功能 public static string JsonPost(string url, string method, string pos
var webRequest = WebRequest.Create(@"http://10.2.1.85/");
它工作正常,但我不知道如何传递用户Id和用户代码。
我必须创建对象还是什么
我该怎么做?这是如何在Web服务上发布数据: webservicepost功能
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");
}
}
您可以使用[WebMethod]属性修饰的方法创建web项目。将web应用部署到服务器或本地。然后在Visual Studio中引用Web服务并调用其方法。在否决和硬编码电子邮件和密码时没有用,对吗?对不起,对于我在LoginUser上添加的参数。现在我删除了这个参数,这样示例就可以为电子邮件和密码设置静态值或硬编码值。无论如何,他总是可以在方法上添加一些电子邮件和密码参数。