Question

I'm trying to download a file from a server and adding authentication and range header in my app, so is this syntax correct?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                        request.Headers["Range"] = "bytes=0-";
                        request.Credentials = new NetworkCredential("username","password");

Of course the code has other parts for reading the file as a stream and storing it but i'm concerned with the range header and authentication part because it's not working.

I get an exception

{"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"}
Was it helpful?

Solution 2

Here is another way to do it

   var httpClientHandler = new HttpClientHandler();
                        httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");
                        var client = new HttpClient(httpClientHandler);
                        System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));
                        request.Headers.Range = new RangeHeaderValue(0, null);
                        HttpResponseMessage response = await client.SendAsync(request);

OTHER TIPS

Here's how to do it:

public async Task<byte[]> DownloadFileAsync(string requestUri)
{
    // Service URL
    string serviceURL = "http://www.example.com";

    // Http Client Handler and Credentials
    HttpClientHandler httpClientHandler = new HttpClientHandler();
    httpClientHandler.Credentials = new NetworkCredential(username, passwd, domain);

    // Initialize Client
    HttpClient client = new HttpClient(httpClientHandler)
    client.BaseAddress = new Uri(serviceURL);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
    // Add Range Header
    client.DefaultRequestHeaders.Add("Range", "bytes=0-");

    // Deserialize
    MemoryStream result = new MemoryStream();
    Stream stream = await client.GetStreamAsync(requestUri);
    await stream.CopyToAsync(result);
    result.Seek(0, SeekOrigin.Begin);

    // Bson Reader
    byte[] output = null;
    using (BsonReader reader = new BsonReader(result))
    {
        var jsonSerializer = new JsonSerializer();
        output = jsonSerializer.Deserialize<byte[]>(reader);
    }
    return output;
}

I'm current using the BSON media format. If you need addtional information regarding BSON in your backend, herre's a great article on how to implement it and consume it: http://www.strathweb.com/2012/07/bson-binary-json-and-how-your-web-api-can-be-even-faster/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top