HttpClient throws error with the Rest services

2019-07-13 18:13发布

I am trying to call multiple rest services from the Web API I am creating and I am getting the below error while one of the Sharepoint rest service is called

This instance has already started one or more requests. Properties can only be modified before sending the first request.

Below is the code for calling the rest services using the HttpClient

try
{
    var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
    var myCache = new CredentialCache();
    myCache.Add(new Uri(core_URL), "NTLM", credential);

    var handler = new HttpClientHandler();
    handler.AllowAutoRedirect = true;
    handler.Credentials = myCache;

    using (var client_sharePoint = new HttpClient(handler))
    {
        var response = client_sharePoint.GetAsync(core_URL).Result;
        client_sharePoint.BaseAddress = uri;
        client_sharePoint.DefaultRequestHeaders.Accept.Clear();
        client_sharePoint.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var responsedata = await response.Content.ReadAsStringAsync();
        var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
            responsedata);

        return returnObj;
    }

    ...

I have never encountered this error before. Can anyone please suggest me if I need set the timeout

1条回答
聊天终结者
2楼-- · 2019-07-13 18:44

Try this:

var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
var myCache = new CredentialCache();
myCache.Add(new Uri(core_URL), "NTLM", credential);

var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;

using (var client_sharePoint = new HttpClient(handler))
{
    client_sharePoint.BaseAddress = uri;
    client_sharePoint.DefaultRequestHeaders.Accept.Clear();
    client_sharePoint.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client_sharePoint.GetAsync(core_URL);

    var responsedata = await response.Content.ReadAsStringAsync();
    var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
        responsedata);

    return returnObj;
}

Headers and BaseAddress must be set before you make the request with GetAsync. I also took the liberty to change from .Result to await since calling .Result is poor practice and I can see this is in an async method.

You should also read this: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

查看更多
登录 后发表回答