简体   繁体   中英

Customize returning JSON from ASP.NET Core API , Values with Statuscode

I'm trying to return back JSON with customization , anyone can help to return the result like this :

{
    status: 200,
    message: "success",
    data: {
        var1: {
        },
        var2: {
        }
    }
}

with this code :

            return Ok(new
            {
                var1,
                var2
            });

Why do you need to use the OkResult object?

A simple way of returning what you'd like is to use dynamic objets, or a class with properties matching the Json you'd like to get, and a JsonResult object.

             dynamic json = new ExpandoObject();
             json.Result = 200;
             json.Message = "success";
             json.Data.var1 = "whatever";
             json.Data.var2 = "something else";

             Response.StatusCode = json.Result; //matches the HTTP Status Code with the one from your json
                return new JsonResult(json);

I used this for taking profile information from google id token , and then generate JWT token from my backend server and retuen back JWT and Profile info for client apps so this is the solution :

var profile = (new RetrnedUserProfile
            {
                Email = payload.Email,
                FirstName = payload.GivenName,
                FamilyName = payload.FamilyName,
                PictureUrl = payload.Picture
            });

            return Ok(new ResponseModel
            {
                StatusCode = HttpStatusCode.OK,
                Message = "success",

                Data = new
                {
                    profile,
                    accessToken
                }
            });

 public class RetrnedUserProfile
{
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
    public string Email { get; set; }
    public string PictureUrl { get; set; }
}

public class ResponseModel
{
    public HttpStatusCode StatusCode { get; set; }
    public string Message { get; set; }
    public object Data { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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