繁体   English   中英

在C#中使用F#类型

[英]Working with F# types in C#

我有一个C#Web API,可用于访问F#库。 我创建了我想返回的类型的DU,并使用模式匹配来选择返回到c#控制器的类型。

在C#控制器中,如何访问从函数调用返回到F#库的类型的数据?

C#控制器

public HttpResponseMessage Post()
{
    var _result = Authentication.GetAuthBehaviour();
    //Access item1 of my tuple
    var _HTTPStatusCode = (HttpStatusCode)_result.item1;
    //Access item2 of my tuple
    var _body = (HttpStatusCode)_result.item2;
    return base.Request.CreateResponse(_HTTPStatusCode, _body);
}

F#类型

module Types =
    [<JsonObject(MemberSerialization=MemberSerialization.OptOut)>]
    [<CLIMutable>]
    type ValidResponse = {
         odata: string;
         token: string; 
    }

    [<JsonObject(MemberSerialization=MemberSerialization.OptOut)>]
    [<CLIMutable>]
    type ErrorResponse = {
         code: string;
         message: string;
         url: string; 
    }

    type AuthenticationResponse = 
    | Valid of int * ValidResponse
    | Error of int * ErrorResponse

F#功能

module Authentication = 
    open Newtonsoft.Json

    let GetAuthBehaviour () =
        let behaviour = GetBehaviour.Value.authentication
        match behaviour.statusCode with
        | 200 ->
            let deserializedAuthenticationResponse = JsonConvert.DeserializeObject<Types.ValidResponse>(behaviour.body)
            Types.Valid (behaviour.statusCode, deserializedAuthenticationResponse)
        | _ ->
            let deserializedAuthenticationResponse = JsonConvert.DeserializeObject<Types.ErrorResponse>(behaviour.body)
            Types.Error (behaviour.statusCode, deserializedAuthenticationResponse)

F#区分联合被编译为抽象类,每种情况都是派生的嵌套类。 在C#中,您可以尝试通过下推GetAuthBehaviour的结果来访问案例:

public HttpResponseMessage Post()
{
    var result = Authentication.GetAuthBehaviour();

    var valid = result as Types.AuthenticationResponse.Valid;
    if (valid != null)
    {
        int statusCode = valid.Item1;
        Types.ValidResponse body = valid.Item2;
        return this.CreateResponse(statusCode, body);
    }

    var error = result as Types.AuthenticationResponse.Error;
    if (error != null)
    {
        int statusCode = error.Item1;
        Types.ErrorResponse body = error.Item2;
        return this.CreateResponse(statusCode, body);
    }

    throw new InvalidOperationException("...");
}

注意,C#编译器不知道您已经处理了所有情况,因此您需要提供一个分支来处理result既不是Valid也不是Error 在这里,我仅以抛出异常为例,但是在Web API中,返回500状态代码可能更合适。

尽管如此,为什么还要用C#编写和维护Controller? 您可以仅使用F#编写ASP.NET Web API

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM