【问题标题】:Empty respond when Post data in C#在 C# 中发布数据时为空响应
【发布时间】:2021-08-16 08:23:01
【问题描述】:

当我发布用户名和密码以及 IP 地址时,我只得到一个空响应。 我的 C# 代码是:

public async void APILogin(string user, string pass, string ip)
{
    var person = new Userinfo { username = user, password = pass, ip = ip };
    var json = JsonConvert.SerializeObject(person);
    var data = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
    var url = new Uri("http://localhost/login/dblogin.php") ;

    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(url,content:data);
    HttpContent content = response.Content;
    string myContent = await content.ReadAsStringAsync();
    MessageBox.Show(myContent, "Info");
}
public class Userinfo 
{
    public String username { get; set; }
    public String password { get; set; }
    public String ip { get; set; }
}

【问题讨论】:

  • 您希望得到什么?响应码是什么?
  • @faso 得到的响应如下:{"message":"success"} or {"message":"wrong password"} or {"message":"user restricted"} or {"message ":"未授权"}
  • 响应的 HTTP 状态码是什么?
  • @faso 它是 200
  • @AmirEslamzadeh Http response code 200 是“成功 HTTP 请求的标准响应”。 PHP 应用程序说一切都很好,这是错误的

标签: c# http-post


【解决方案1】:

我用过这个,效果很好。

var url = "http://localhost/login/dblogin.php";
            HttpClient client = new HttpClient();
            StringContent data = new StringContent("username="+user+"&password="+pass+"&ip="+ip);
            data.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
            HttpResponseMessage response = await client.PostAsync(url, data);
            response.EnsureSuccessStatusCode();
            HttpContent content = response.Content;
            string myContent = await content.ReadAsStringAsync();
            loginResp apiResponse = JsonConvert.DeserializeObject<loginResp>(myContent);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2021-10-08
    • 1970-01-01
    • 2016-11-29
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多