[英]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 :我正在尝试通过自定义返回 JSON,任何人都可以帮助返回这样的结果:
{
status: 200,
message: "success",
data: {
var1: {
},
var2: {
}
}
}
with this code :使用此代码:
return Ok(new
{
var1,
var2
});
Why do you need to use the OkResult object?为什么需要使用 OkResult 对象?
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.返回您想要的内容的一种简单方法是使用动态对象,或具有与您想要获取的 Json 匹配的属性的类,以及一个 JsonResult 对象。
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 :我用它来从 google id token 获取配置文件信息,然后从我的后端服务器生成 JWT 令牌并返回客户端应用程序的 JWT 和配置文件信息,所以这是解决方案:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.