本文主要是介绍【asp.net】api后端返回前端json格式和字符串格式样式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
// #################################################################################### 【Login2】[HttpPost]public HttpResponseMessage LoginApi([FromBody]Body model){// 创建一个对象来保存要返回的数据var result = new { username = "csj", password = "123" };// 序列化对象为 JSON 格式string jsonResult = JsonConvert.SerializeObject(result);// 创建一个 HttpResponseMessage 对象,并设置其 Content 为 JSON 格式的字符串var response = new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent(jsonResult, System.Text.Encoding.UTF8, "application/json")};return response;}
二、另一种形式
// #################################################################################### 【Login2】[HttpPost]public HttpResponseMessage LoginApi([FromBody]Body model){LogManager.WriteLog("========LoginApi - 888 ===========");//string Sql_Body = model.BodyValue; // 【表名】//string Sql_Table = Json_Read.Json_KeyValueArray(Sql_Body, "username"); // 【表名】 "Time_Task"//LogManager.WriteLog(Sql_Table);string jsonString = @"{""code"": 0,""message"": ""ok"",""data"": {""token"": ""eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLmtYvor5Xmiafms5XkurrlkZgiLCJleHAiOjE3MjQ2Njc2NjIsImlhdCI6MTcyNDY2MDQ2Mn0.r_cBg4YvklKKRAMj5FtAcRzKcYI4iIgAAlrULL_7SvU""}}";// 将 jsonString 包装成 HttpResponseMessagevar response = new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")};return response;}
这篇关于【asp.net】api后端返回前端json格式和字符串格式样式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!