none
error while copying content Web API RRS feed

  • Question

  • Http Client throwing error : error while copying content 

    This is my code

                serverUrl = GetServerUri(serverUrl);
                HttpContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
                HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
                client.BaseAddress = new Uri(serverUrl);
                content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
                client.DefaultRequestHeaders.Accept.Add(
                   new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.PostAsync(url, content).Result;
                return response.Content.ReadAsStringAsync().Result;

    It works fine when i deploy web api in root level.  like : http:\\servername\api\controller\method

    But when i deploy web api like this :  http:\\servername\apiname\api\controller\method

    This throws this exception.

    Any idea ? 

    Monday, April 9, 2018 7:29 AM

All replies

  • Why don't you try posting the exception message? But make your post to the below forum.

    https://forums.asp.net/1246.aspx/1?Web+API

    Monday, April 9, 2018 10:43 AM
  • "Error while copying content to a stream"

    This is the exception which i am getting. 

    Monday, April 9, 2018 10:49 AM
  • Firstly URL slashes go the other way.

    var url = http://servername/apiname/api/controller/method

    Secondly, put a slash at the end of your server URL.

    //Won't work
    var serverUrl = "http://servername/apiname";
    
    //Will work
    var serverUrl = "http://servername/apiname/";

    The issue is that Uri doesn't combine URLs the way you'd expect. Under the hood HttpClient will store the BaseAddress value in a Uri. Then when you call the various Get/Post methods you pass a resource. You'd assume that HttpClient would simply concat the 2 but it doesn't. Instead it calls into Uri to combine the URLs. Uri looks at the left and right sides of the given paths. On the left side it assumes you have a domain/path already so it strips the path off the left URL and then concats the right URL. Hence you lose apiname. However if you end the URL with a slash then it sees an empty path and simply concats the right side.

    Personally I have an extension method called EnsureEndsWith on strings and I use it to ensure the URL is appended with a slash at the point it calls Uri. Cuts down the chances of errors.


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Stanly Fan Tuesday, April 10, 2018 1:32 AM
    Monday, April 9, 2018 3:00 PM
    Moderator