我在 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),但是当我在 Controller 中进行中断时,我看到 C# 类仅公开其公共(public)属性,而 F# 类同时具有 Property和暴露的背景场。我尝试在 F# let 语句中添加“private”关键字,但得到了以下结果:
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/
关于asp.net-web-api - 在 C# WebApi/MVC 项目中,用 F# 创建的类序列化不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281461/