HttpClient post 参数在 body

HttpClient post with parameters in body

我成功地使用 postman 执行 post 进行身份验证,但似乎无法从 C# 运行它,得到 401。密码和用户名的验证与post伙计。有任何想法吗?这是我的代码:

            var url = AppConstants.ApiLoginUrl;
            var uriRequest = new Uri(url);
            string httpResponseBody;

            using (var httpClient = new Windows.Web.Http.HttpClient())
            { 
              var content = new HttpStringContent(string.Format("username={0}&password={1}", email, password), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                try
                {
                    var httpResponse = await httpClient.PostAsync(uriRequest, content); 

... }

以下是 Postman 中 header 和 body 的设置。

现在将此代码用于内容参数:

                var content = new HttpFormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("username", email),
                    new KeyValuePair<string, string>("password", password)
                });

仔细观察,用户名似乎在 Fiddler 中针对 Postman 和代码请求进行了编码。因此,我关于使用编码用户名的理论并不完全正确。这里是来自 Fiddler 的请求的快照...还有更多 suggestions/ideas?

邮递员headers:

代码headers:

原始视图 Postman * 显示编码的用户名字段:

原始视图代码

尝试将您的内容更改为以下内容

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("username", email),
    new KeyValuePair<string, string>("password", password)
});

我正在使用此函数发送 post 带有参数的请求,Dictionary<string, string> data 是否如 Web 服务所期望的那样作为键值

public static T PostCast<T>(string url, Dictionary<string, string> data)
{
    using (HttpClient httpClient = new HttpClient())
    {
        var response = httpClient.PostAsync(url, new FormUrlEncodedContent(data)).Result;
        return response.Content.ReadAsAsync<T>().Result;
    }
}

希望对您有所帮助:)

我的理解是,对于 UWP 应用,Windows.Web.Http.HttpClient() 是推荐的方法,另外请确保您的 URL 没有拼写错误。 :)

         var url = AppConstants.ApiLoginUrl;
            var uriRequest = new Uri(url);

            var content = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("username", email),
                new KeyValuePair<string, string>("password", password)
            });

            using (var httpClient = new Windows.Web.Http.HttpClient())
            {
                try
                {
                    var httpResponse = await httpClient.PostAsync(uriRequest, content); 

我遇到了同样的问题,并通过从 HttpClient 发布到的 URL 中删除尾随的“/”来修复它。