Classes created in F# serialized incorrectly in a C# WebApi/MVC project

时光毁灭记忆、已成空白 提交于 2019-12-11 03:26:08

问题


I created a class in FSharp like so:

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

When I reference the project from my C# WebAPI/MVC application like this

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

I am getting the following results. Note that the field name are camelCased.

<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>

When I create a similar class in C# like this

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

the output is Pascal cased

<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>    

I first thought it was the Json Serializer (Newtonsoft by default I think), but when I put a break in the controller, I see that the C# class only has its public properties exposed and that the F# class has both the Property and the backing field exposed. I tried to add a "private" keyword to the F# let statements but I got this:

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. 

So is there a way that the F# classes can treated the same as C# from Web Api?


回答1:


See Mark's blog on this very issue: http://blog.ploeh.dk/2013/10/15/easy-aspnet-web-api-dtos-with-f-climutable-records/



来源:https://stackoverflow.com/questions/26281461/classes-created-in-f-serialized-incorrectly-in-a-c-sharp-webapi-mvc-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!