繁体   English   中英

RestSharp异步PUT

[英]RestSharp asynchronous PUT

有一个应用程序,即具有访问数据库权限的API和一个使用RestSharp调用该API的应用程序。 我实现了RestSharp的所有异步方法来正常工作。 所以GET,POST,DELETE都可以使用,我唯一无法使用的就是PUT。

首先,这是我的控制器PUT:

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

这是我的方法:

 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;
    }

这是我在视图中的调用(所有其他GET,...调用都工作正常):

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

通过调试,响应状态已Completed但从未调用PUT。

知道可能是什么问题吗?

所以最后我自己得到了答案...(昨天坐了6个小时,没有结果,今天又坐了一个小时,就可以了)

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;
}

诀窍是添加一个RequestFormat并将AddObject更改为AddBody :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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