-1

我收到了对我的 api (x-www-form-urlencoded) 的发布请求,请求的正文如下所示:

worker=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261asd23e9231241dfd2b4c3bd%22%7D%2C+%22sid%22%3A+%22WKb32df49cas43413585352e8a6e2%cd%22%22%%22%3A+1234154123%7D%7D&task=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261caffc34dsf33182b4c789

继续。在这个传入的请求中我需要接收2个对象(类),我创建了这2个对象的类结构: 例如,我的类结构如下:

public class Worker
{
    [JsonProperty("friendly_name")]
    public string FriendlyName { get; set; }

    [JsonProperty("date_updated")]
    public WorkerDateUpdated DateUpdated { get; set; }

    [JsonProperty("activity")]
    public string Activity { get; set; }

    [JsonProperty("workspace_sid")]
    public string WorkspaceSid { get; set; }

    [JsonProperty("date_created")]
    public WorkerDateCreated DateCreated { get; set; }

    [JsonProperty("queues")]
    public List<string> queues { get; set; }
 }

public class Task
{
    [JsonProperty("reason")]
    public string Reason { get; set; }

    [JsonProperty("date_updated")]
    public TaskDateUpdated DateUpdated { get; }

    [JsonProperty("assignment_status")]
    public string AssignmentStatus { get; set; }

    [JsonProperty("total_cost")]
    public TaskTotalCost TotalCost { get; set; }
}

在传入的请求中,我收到 3 个作为 url 编码的对象(类),我只需要 2 个对象及其属性。

 using (var reader = new StreamReader(
                                              HttpContext.Request.Body,
                                              encoding: Encoding.UTF8,
                                              detectEncodingFromByteOrderMarks: false
                                       ))
            {
                var bodyString = await reader.ReadToEndAsync();

                _logger.LogInformation("BodyString ---> " + bodyString);

                var decodedUrl = HttpUtility.UrlDecode(bodyString);
               _logger.LogInformation(" decodedUrl ---> " + decodedUrl);
}

我可以读取传入的正文并将其转换为解码格式。下面是一个例子:

   worker={"_id": {"$oid": "XXXXXXXXXX"}, "sid": "XXXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXX", "queues ": ["XXXXXXXXXXXXXX"], "activity": "idle", "available": true, "friendly_name": "XXXXXXXX", "attributes": {"mail": "XXXXXXXXXXXX", "name": "XXXXXXXXXX" }, "date_created": {"$date": XXXXXXXXX}, "date_updated": {"$date": XXXXXXXXXX}, "date_status_changed": {"$date": XXXXXXXXXXXXX}}&task={"_id": {" $oid": "XXXXXXXXXXXXXX"}, "sid": "XXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXXXXXXXX", "workflow_sid": "XXXXXXXXXXXX", "workflow_friendly_name" : "daytime1", "initial_attributes": {"station_name": "XXXXX", "component_type": X, "component_id": XXX, "mail": "XXXXXX", "main_issue": "XXXXXXXXXXXXXX", "predictivi_maintenance_time": "XXXXXXXXXX", "hospital_name": "\u00dcsk\u00fcdar XXXXXXXXXXX"}

我可以看到它,但我不能反序列化它。或者我不知道我是否做错了。我创建了一个单独的类,其中包含我的 2 个类。我将 Worker 和 Task 类保留在其中,我无法反序列化到该类,它不会以任何方式反序列化。意外的字符引发异常。如何将这些对象转换为 json 格式或对象格式?

编辑:我的其他自定义课程:

public class TaskDateUpdated
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}
public class TaskTotalCost
{
    [JsonProperty("$numberDecimal")]
    public string NumberDecimal { get; set; }
}

public class TaskDateCreated
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}

public class TaskLastChargeDate
{
    [JsonProperty("$date")]
    public long Date { get; set; }
}
public class TaskId
{
    [JsonProperty("$oid")]
    public string Oid { get; set; }
}

 public class WorkerDateUpdated
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

public class WorkerDateCreated
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

public class WorkerDateStatusChanged
{
    [JsonProperty("$date")]
    public long date { get; set; }
}

我也有一个包含这两个类的类,当我尝试反序列化到这个类时出现错误,当我尝试将它分别反序列化到其他工作人员和任务类时也会出现错误。我根本无法反序列化。

public class DataContainer
{
    public Task Task { get; set; }
    public Worker Worker { get; set; }
}

我的 post 方法如下所示:

     [HttpPost]
     [Consumes("application/x-www-form-urlencoded")]
     public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
    {
      using (var reader = new StreamReader(
                                           HttpContext.Request.Body,
                                           encoding: Encoding.UTF8,
                                              detectEncodingFromByteOrderMarks: false
                                       ))
            {
                var bodyString = await reader.ReadToEndAsync();

                _logger.LogInformation("BodyString ---> " + bodyString);

                var decoded = HttpUtility.UrlDecode(bodyString);

                //here is where i need to deserialize and convert it to 
                //a valid json and object
            }
    }
4

1 回答 1

0

您可以使用HttpUtility.ParseQueryString将其解析为NameValueCollection,然后只需使用索引器即可["worker"]

 [HttpPost]
 [Consumes("application/x-www-form-urlencoded")]
 public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
 {
     using (var reader = new StreamReader(
                                        HttpContext.Request.Body,
                                        encoding: Encoding.UTF8,
                                           detectEncodingFromByteOrderMarks: false
                                    ))
     {
         var bodyString = await reader.ReadToEndAsync();
         var decoded = HttpUtility.ParseQueryString(bodyString);
         var worker = JsonSerializer.Deserialize<Worker>(decoded["worker"]);
         var task = JsonSerializer.Deserialize<Task>(decoded["task"]);
                          // or whatever your JSON deserializer is
     }
 }

在较新版本的 ASP.net Core 中,您可以使用HttpContext.Request.Form

 [HttpPost]
 [Consumes("application/x-www-form-urlencoded")]
 public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
 {
     var worker = JsonSerializer.Deserialize<Worker>(HttpContext.Request.Form["worker"]);
     var task = JsonSerializer.Deserialize<Task>(HttpContext.Request.Form["task"]);        // or whatever your JSON deserializer is
 }
于 2021-12-29T15:18:55.187 回答