如何将JSON传输到asp.net中的POST api并转换为数据模型

问题描述 投票:0回答:1

我对 API 的经验很少。我正在尝试使用 HttpPost 请求将有关查看产品记录的数据从我的移动应用程序 .NET MAUI 传输到服务器 ASP.NET。我正在尝试使用字符串内容以 JSON 的形式从移动客户端传输数据,如文档中所建议的那样。但我仍然找不到有关如何获取此 JSON 并将其转换为 View 类的实例的信息。

我的 API HttpPost 代码:

[Route("api/[controller]")]
[ApiController]
public class ViewController : ControllerBase
{

    // POST api/<ViewController>
    [HttpPost]
    public async void Post(int id, DateOnly date, TimeOnly time)
    {
        using (VapeshopContext db = new VapeshopContext())
        {
            View view = new View
            {
                Date = date,
                Time = time,
                ProductId = id
            };
            db.Views.Add(view);
            await db.SaveChangesAsync();
        }
    }    
}

我的 POST 请求代码:

 private async void toInfoPage(object obj)
 {
     if (obj != null)
     {         
         var p = obj as Product;
         using StringContent jsonContent = new(
             JsonSerializer.Serialize(new
             {
                 Date = DateOnly.FromDateTime(DateTime.Now),
                 Time = TimeOnly.FromDateTime(DateTime.Now),
                 ProductId = p.Id
             }),
             Encoding.UTF8, "application/json");
         await httpClient.PostAsJsonAsync("http://10.0.2.2:5125/api/View",jsonContent);

        var newPage = new ProductInfo(obj as Product);
        await Navigation.PushAsync(newPage);
     }
 }
c# asp.net maui asp.net-apicontroller
1个回答
0
投票

您可以将您的

POST
身体转换为
Model
:

public class MyObjectModel
{
    public int ProductId {get;set;}
    public DateOnly Date {get;set;}
    public TimeOnly Time {get;set;}
}

并将您的

toInfoPage
方法更改为:

 private async void toInfoPage(object obj)
 {
     if (obj != null)
     {         
         var p = obj as Product; 
         using StringContent jsonContent = new(
             JsonSerializer.Serialize(new MyObjectModel
             {
                 Date = DateOnly.FromDateTime(DateTime.Now),
                 Time = TimeOnly.FromDateTime(DateTime.Now),
                 ProductId = Convert.ToInt32(p.Id)
             }),
             Encoding.UTF8, "application/json");
             
         await httpClient.PostAsJsonAsync("http://10.0.2.2:5125/api/View",jsonContent);

        var newPage = new ProductInfo(obj as Product);
        await Navigation.PushAsync(newPage);
     }
 }

最后使用

MyObjectModel 
属性在端点检索
FromBody

[Route("api/[controller]")]
[ApiController]
public class ViewController : ControllerBase
{

    // POST api/<ViewController>
    [HttpPost]
    public async void Post([FromBody] MyObjectModel model)
    {
        using (VapeshopContext db = new VapeshopContext())
        {
            View view = new View
            {
                Date = model.Date,
                Time = model.Time,
                ProductId = model.ProductId
            };
            db.Views.Add(view);
            await db.SaveChangesAsync();
        }
    }    
}
© www.soinside.com 2019 - 2024. All rights reserved.