411 - 尝试POST时需要长度

时间:2016-10-21 18:13:41

标签: c# .net http mobile xamarin

我正在使用Xamarin开发移动应用程序。这使得我无法调用webRequest.ContentLength = 0。

以下是我试图发布的内容:

客户来电:

await new AssetEndpoint().UpdateStatus(Authentication, CurrentAsset, ApprovalStatuses[0]);

AssetEndpoint.UpdateStatus:

public Task UpdateStatus(Authentication auth, Asset asset, ApprovalStatus newStatus)
{
    return PostResponseAsync(auth, string.Format(
        ApiUpdateStatus, asset.UID, newStatus.Id));
}

Endpoint.PostResponseAsync:

protected async Task<string> PostResponseAsync(Authentication auth, string apiCall)
{
    var request = WebRequest.Create(string.Concat(BaseUriPath, apiCall)) as HttpWebRequest;
    request.ContentType = "application/json";
    request.Method = method;
    request.Headers["Authorization"] = string.Concat("bearer ", auth.Token.Value);
    var response = await request.GetResponseAsync().ConfigureAwait(false);
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        return await reader.ReadToEndAsync();
    }
}

所以我去修复此错误?我似乎无法弄清楚如何设置内容长度。

2 个答案:

答案 0 :(得分:0)

这可能是您正在使用的Xamarin版本中的问题:

http://forums.xamarin.com/discussion/comment/58076#Comment_58076

答案 1 :(得分:-1)

public class RestClientTest
{
    public static async Task<string> Login()
    {
        try
        {
            var request = WebRequest.CreateHttp(path);
            request.Headers["Username"] = "xxxxxxxxx";
            request.Headers["Password"] = "xxxxxxxxxxx";
            request.ContentType = "application/json";
            request.Method = "POST";
            byte[] byteArray = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35 };
            using (Stream dataStream = await request.GetRequestStreamAsync())
            {
                await dataStream.WriteAsync(byteArray, 0, byteArray.Length);
            }
            var response = await request.GetResponseAsync().ConfigureAwait(false);
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                string resp = await reader.ReadToEndAsync();
                return resp;
            }
        }
        catch (Exception ex)
        {
            return "Error";
        }
    }
}

如果这对您不起作用,我可以提供HttpClient示例,如果您想尝试。如果不知道你发布了什么,我就无能为力了。我还测试了这段代码而没有在正文中发送任何数据,它也有效。