首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在asp.net中将json补丁数据与rest客户端一起传递?

如何在asp.net中将json补丁数据与rest客户端一起传递?
EN

Stack Overflow用户
提问于 2020-10-03 11:11:28
回答 1查看 255关注 0票数 0

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

代码语言:javascript
复制
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);
    });
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-04 12:35:32

这很简单。在查看了stackoverflow上的类似问题后,我最初尝试了以下内容:

代码语言:javascript
复制
var body = new
            {
                op = "replace",
                path = "/FirstName",
                value = "John"
            };
            
restRequest.AddParameter("application/json-patch+json", body, ParameterType.RequestBody);

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

代码语言:javascript
复制
restRequest.AddJsonBody(request.patchParams);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64180346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档