【问题标题】:Serializing an object with restsharp and passing it to WebApi not serializing list用restsharp序列化一个对象并将其传递给WebApi而不是序列化列表
【发布时间】:2015-08-04 17:30:35
【问题描述】:

我有一个看起来像的视图模型。

public class StoreItemViewModel
{
    public Guid ItemId { get; set; }
    public List<Guid> StoreIds { get; set; }
    [Required]
    public string Description { get; set; }
    //[Required]
    //[DataMember(IsRequired = true)]
    public int ItemTypeId { get; set; }


}

我有一个使用 RestSharp 的小帮手。

public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
    {
        var client = new RestClient(CreateBaseUrl(null))
        {
            Authenticator = new HttpBasicAuthenticator("user", "Password1")
        };

        var request = new RestRequest(apiEndPoint, Method.POST);
        //request.JsonSerializer = new JsonSerializer();
       // {RequestFormat = DataFormat.Json};
        request.AddObject(objectToUpdate);
       // clientJsonSerializer = new YourCustomSerializer();
        var response = client.Execute<T>(request);
        return response;
    }

在我的 api 中调试控制器时

 [HttpPost]
    public HttpResponseMessage Create([FromBody]StoreItemViewModel myProduct)
    {
        //check fields are valid
     .........
     }

myProducts 产品除了公共 List StoreIds 之外都被填充,它总是返回带有空 Guid 的单个奖励​​。即使我添加了 2 个或更多 StoreIds

我认为这是因为我在我的应用程序中使用我的 Create 助手做错了。

任何人都可以帮助解决这个问题。

发送到 webapi 的原始数据是这样的

ItemId=f6dbd244-e840-47e1-9d09-53cc64cd87e6&ItemTypeId=6&Description=blabla&StoreIds=d0f36ef4-28be-4d16-a2e8-37030004174a&StoreIds=f6dbd244-e840-47e1-9d09-53cc64cd87e6&StoreId=d0f36ef4-28be-4d16-a2e8-37030004174a

【问题讨论】:

  • 你能分享一下原始 json 请求的样子吗?
  • @KiranChalla 抱歉,我该如何使用 restsharp 位?
  • 您可以使用 Fiddler,它是一个 httpproxy,来捕获请求/响应。
  • 哈哈我不知道我可以使用 fiddler 来处理服务器端的东西。我一直认为这只是为了客户端的东西。感谢您的提示 :) 我刚刚用原始 json 更新了帖子
  • 所以我已经看到当数据被序列化时 StoreIds 设置不正确。我尝试使用 json.net 库进行测试,它工作正常。如果我需要使用 json.net 库,我很乐意这样做,我只是不知道如何将 json.net 序列化对象传递给 api

标签: c# asp.net-mvc asp.net-web-api json.net restsharp


【解决方案1】:

RestSharp 现在有一种更简化的方式来使用 Json 序列化将对象添加到 RestRequest 主体:

public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
{
    var client = new RestClient(CreateBaseUrl(null))
    {
        Authenticator = new HttpBasicAuthenticator("user", "Password1")
    };
    var request = new RestRequest(apiEndPoint, Method.POST);
    request.AddJsonBody(objectToUpdate); // HERE
    var response = client.Execute<T>(request);
    return response;
}

这是在 RestSharp 105.0.1.0 中找到的

【讨论】:

    【解决方案2】:

    我设法让这个工作。我不认为它是正确的方法,但它有效。

     public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
        {
            var client = new RestClient(CreateBaseUrl(null))
            {
                Authenticator = new HttpBasicAuthenticator("user", "Password1")
            };
            var json = JsonConvert.SerializeObject(objectToUpdate);
            var request = new RestRequest(apiEndPoint, Method.POST);
            request.AddParameter("text/json", json, ParameterType.RequestBody);
            var response = client.Execute<T>(request);
            return response;
        }
    

    【讨论】:

    • 这个解决方案对我有用。但是,我确实必须使用“application/json”而不是“text/json”。谢谢!
    • 嘿,你有没有找到官方的方法来做到这一点?
    【解决方案3】:

    我遇到了同样的问题并想出了一个可行的解决方案。

    1. 请务必将请求格式设置为 JSON:

      request.RequestFormat = DataFormat.Json;

    2. 使用 AddBody,而不是 AddObject:

      request.AddBody(zNewSessionUsage);

    所以你的代码应该是这样的:

    public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
    {
        var client = new RestClient(CreateBaseUrl(null))
        {
            Authenticator = new HttpBasicAuthenticator("user", "Password1")
        };
    
        var request = new RestRequest(apiEndPoint, Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(objectToUpdate);
        var response = client.Execute<T>(request);
        return response;
    }
    

    【讨论】:

    • 根据上面的示例,.RequestFormat 必须在 .AddBody 之前列出,否则它仍将默认为 XML 序列化。
    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多