F # WebApi returns properly formatted json from discriminatory union

I was wondering what the easiest way would be to return pure json from the result of discriminatory union in WebApi? This use case is for business logic only and not for HTTP errors, etc. - they are processed in the pipeline and returned to the user as usual (404, 500, etc.).

For instance:

type ServiceResult<'a> = { Message:string; Payload:'a }

type ServiceResponse<'a> =
    | Success of ServiceResult<'a>
    | Fail of ServiceResult<string>

Returns either:

{
  "Case": "Fail",
  "Fields": [
    {
      "Message": "Error performing business logic, your x is not in the y.",
      "Payload": "I just couldnt do it"
    }
  ]
}

... or...

{
  "Case": "Success",
  "Fields": [
    {
      "Message": "",
      "Payload": { "FirstName": "Johnny", "LastName":"Smith" }
    }
  ]
}

Where I would like to return only the result of the service, for example:

{
  "Message": "",
  "Payload": { "FirstName": "Johnny", "LastName":"Smith" }
}

... or...

{
  "Message": "Error during operation due to spite.",
  "Payload": "I just couldnt do it"
}

I tried IdiomaticDuConverter: https://gist.github.com/isaacabraham/ba679f285bfd15d2f53e

but he did not work. The closest I've seen is Microsoft.FSharpLu.Json, but it does not have MediaTypeFormatter to connect to the pipeline.

, Lu MediaTypeFormatter, , (, - Json.Net, ).

?

: -)

+4
2

, , , , API HTTP. ASP.NET Web API HTTP-,

{
  "Success": false,
  "Message": "Error during operation due to spite.",
  "Payload": "I just couldnt do it"
}

, 200 OK. , HTTP ( ), , 200 OK .

, , HTTP.

F #. - :

member this.Get() =
    let result = // produce the result somehow...
    match result with
    | Success x -> this.Ok x :> IHttpActionResult
    | Fail msg  -> this.BadRequest msg :> IHttpActionResult

400 Bad Request Fail, , , 500 Internal Server Error .

+3

JSON.NET ServiceResponse, case ServiceResult.

? / , DU . , , , , , :

Success <| { Success = false; Message = "necktie"; Payload = "bacon" }

, ?

+1

Source: https://habr.com/ru/post/1656764/


All Articles