如何将json补丁数据传递给asp.net中的rest客户端



我们使用rest api来获取客户信息。许多GET请求已经由其他人编写。我能够按照他们的代码创建其他GET请求,但更新客户的API方法之一需要使用json补丁。下面我粘贴了一个当前GET方法的示例代码、一个Patch方法(我不知道如何实现(和一个用javascript编写的关于如何使用来自api创建者演示文档的json补丁的示例函数:

public GetCustomerResponse GetCustomerInfo(CustomerRequest request)
{
//All of this works fine the base url and token info is handled elsewhere
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.GET);
var response = CreateRestClient().Execute<GetCustomerResponse>(restRequest);
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new GetCustomerResponse(response.Content);
}   
}
public EditCustomerResponse EditCustomer(EditCustomerRequest request)
{
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.PATCH);
var response = CreateRestClient().Execute<EditCustomerResponse>(restRequest);
//how do I pass along json patch data in here???
//sample json might be like:
//[{'op':'replace','path':'/FirstName','value':'John'},{'op':'replace','path':'/LastName','value':'Doe'}]

if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new EditCustomerResponse(response.Content);
}
}

//javascript demo version that is working
function patchCustomer(acctId, patch, callback) {
var token = GetToken();
$.ajax({
method: 'PATCH',
url: BaseURI + 'customer/account?id=' + acctId,
data: JSON.stringify(patch),
timeout: 50000,
contentType: 'application/json; charset=UTF-8',
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token) },
}).done(function (data) {
if (typeof callback === 'function')
callback.call(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus);
console.error(errorThrown);
failureDisplay(jqXHR);
});
}

这非常简单。在stackoverflow上看到类似的问题后,我最初尝试了这样的东西:

var body = new
{
op = "replace",
path = "/FirstName",
value = "John"
};

restRequest.AddParameter("application/json-patch+json", body, ParameterType.RequestBody);

这是行不通的。为了让它发挥作用,我添加了一个具有op、path和value属性的patchparameters类,然后将patchparametries类型的列表属性添加到我的EditCustomerRequest类中,并像这样使用它:

restRequest.AddJsonBody(request.patchParams);

最新更新