简体   繁体   中英

RestSharp asynchronous PUT

There is one application, the API with access to the database and one application that calls the API with RestSharp. I implemented all async methods of RestSharp to work generic. So GET, POST, DELETE are all working.The only one I can't get to work is the PUT.

First of all this is my controllers PUT:

[HttpPut("{id}")]
public void Put(int id, [FromBody]ApplicationUser value)
{
    string p = value.Email;
}

this is my method:

 public Task<bool> PutRequestContentAsync<T>(string resource, object id, T resourceObject) where T : new()
    {
        RestClient client = new RestClient("http://localhost:54008/api/");
        RestRequest request = new RestRequest($"{resource}/{{id}}", Method.PUT);
        request.AddUrlSegment("id", id);
        request.AddObject(resourceObject);
        var tcs = new TaskCompletionSource<bool>();

        var asyncHandler = client.ExecuteAsync<T>(request, r =>
        {
            tcs.SetResult(r.ResponseStatus == ResponseStatus.Completed);
        });

        return tcs.Task;
    }

and this is my call in a view (all other calls of GET,... are working fine):

bool putOk = await new RepositoryCall()
    .PutRequestContentAsync("Values", 2, 
        new ApplicationUser { 
            Email="test@xxxxxxx.de" 
        }
    );

with debugging, the response-status is Completed but the PUT is never called.

Any idea what the problem could be?

So finally I got my answer myself... (sit yesterday 6 hours and no result, today one more hour and it works)

public Task<bool> PutRequestContentAsync<T>(string resource, object id, T resourceObject) where T : new()
{
    RestClient client = new RestClient("http://localhost:54008/api/");
    RestRequest request = new RestRequest($"{resource}/{{id}}", Method.PUT);
    request.AddUrlSegment("id", id);

    request.RequestFormat = DataFormat.Json;
    request.AddBody(resourceObject);

    var tcs = new TaskCompletionSource<bool>();

    var asyncHandler = client.ExecuteAsync<T>(request, (response) => {
        tcs.SetResult(response.ResponseStatus == ResponseStatus.Completed);
    });
    return tcs.Task;
}

the trick was to add a RequestFormat and changing AddObject to AddBody :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM