C# 使用restsharp序列化对象并将其传递给WebApi而不是序列化列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12260465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:40:09  来源:igfitidea点击:

Serializing an object with restsharp and passing it to WebApi not serializing list

c#asp.net-mvcasp.net-web-apijson.netrestsharp

提问by Diver Dan

I have a a view model that looks like.

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

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


}

I have a small helper that using is using RestSharp.

我有一个使用 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;
    }

When debugging the controller within my api

在我的 api 中调试控制器时

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

myProducts products are all populated apart from the public List StoreIds it always is returning a single reward with an empty Guid. Even if I have added 2 or more StoreIds

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

I assume this is because I am doing something wrong with my Create helper within my application.

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

Can anyone help with this its causing a major headache.

任何人都可以帮助解决这个问题,这会导致严重的头痛。

The raw data sent to the webapi is looking like

发送到 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

采纳答案by Diver Dan

I managed to get this working. I don't think its the correct way but it works.

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

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

回答by bigtech

I struggled with the same problem and came up a working solution.

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

  1. Be sure to set the request format to JSON:

    request.RequestFormat = DataFormat.Json;

  2. Use AddBody, rather than AddObject:

    request.AddBody(zNewSessionUsage);

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

    request.RequestFormat = DataFormat.Json;

  2. 使用 AddBody,而不是 AddObject:

    request.AddBody(zNewSessionUsage);

So your code would be something like this:

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

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

回答by Paddy

RestSharp now has a more streamlined way to add an object to the RestRequest Body with Json Serialization:

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

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

This was found in RestSharp 105.0.1.0

这是在 RestSharp 105.0.1.0 中发现的