在 C# WebApi/MVC 项目中,用 F# 创建的类序列化不正确

2023-12-27

我在 FSharp 中创建了一个类,如下所示:

type Account() = class
    let mutable amount = 0m
    let mutable number = 0
    let mutable holder = ""

    member this.Number
        with get () = number
        and set (value) = number <- value

    member this.Holder
        with get () = holder
        and set (value) = holder <- value

    member this.Amount
        with get () = amount
        and set (value) = amount <- value

end

当我像这样从 C# WebAPI/MVC 应用程序引用该项目时

[HttpGet]
public Account Index()
{
    var account = new Account();
    account.Amount = 100;
    account.Holder = "Homer";
    account.Number = 1;
    return account;
}

我得到以下结果。请注意,字段名称采用驼峰式命名。

<Account xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ChickenSoftware.MVCSerializationIssue">
<amount>100</amount>
<holder>Homer</holder>
<number>1</number>
</Account>

当我像这样在 C# 中创建类似的类时

public class NewAccount
{
    public int Number { get; set; }
    public String Holder { get; set; }
    public int Amount { get; set; }
}

输出是帕斯卡情况

<NewAccount xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ChickenSoftware.MVCSerializationIssue.Api.Models">
<Amount>100</Amount>
<Holder>Homer</Holder>
<Number>1</Number>
</NewAccount>    

我首先以为它是 Json Serializer(我认为默认为 Newtonsoft),但是当我在控制器中进行中断时,我看到 C# 类仅公开其公共属性,而 F# 类同时具有 Property 和 backing场暴露。我尝试将“private”关键字添加到 F# let 语句中,但得到了以下结果:

Error   1   Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. 

那么有没有一种方法可以让 Web Api 中的 F# 类与 C# 类一样对待呢?


请参阅 Mark 关于这个问题的博客:http://blog.ploeh.dk/2013/10/15/easy-aspnet-web-api-dtos-with-f-climutable-records/ http://blog.ploeh.dk/2013/10/15/easy-aspnet-web-api-dtos-with-f-climutable-records/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# WebApi/MVC 项目中,用 F# 创建的类序列化不正确 的相关文章

随机推荐