将json或文本值分配给模型视图

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

我有一个模型视图类:

public class ClientModelView : BaseModelView
{
    public int ClientId { get; set; }
    public int? ClientTypeId { get; set; }
    public int? DisciplineId { get; set; }
    public string ClientName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public AddressModelView Address { get; set; }
    public ClientTypeModelView ClientType { get; set; }
    public DisciplineModelView Discipline { get; set; }
    public bool EmailConfirmed { get; set; }
}

我正在研究 Stripe 集成,通过 webhook 将客户端信息发送到我的应用程序。

我正在向我的应用程序端点发送 JSON 数据发布请求。我以字符串格式获取它。我需要将该 JSON 请求转换为模型视图控制器。

JSON 请求如下所示:

{ 
    "ClientName":"ABC client",
    "firstName": "ABC",
    "lastName": "Client",
    "email": "[email protected]",
    "Address":
        [
            { 
                "Type":"Client", 
                "DisplayAddress":"123 test Dr, test WA 6010",
                "Street1":"123 test Dr",
                "Suburb":"test",
                "Postcode":"6010",
            }
        ]
}

我有以下 webhook 代码:

[HttpPost]
public async Task<IHttpActionResult> Index()
{
    string result = await Request.Content.ReadAsStringAsync();
    ClientModelView client = result; //failed to assign json request string to client model object
    return ok();
}

如何将 JSON 请求字符串分配给客户端模型对象?

json asp.net-mvc post asp.net-web-api http-post
1个回答
0
投票

您为什么认为可以将

string
值分配给
ClientModelView
对象?这显然没有进行类型检查。

您可以尝试将字符串解析为您想要的对象。使用 JsonSerializer.Deserialize 这样的东西应该可以工作:

[HttpPost] public async Task<IHttpActionResult> Index() { string result = await Request.Content.ReadAsStringAsync(); var client = JsonSerializer.Deserialize<ClientModelView>(result); return ok(); }
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.