如何在Web API中为对象类构建[HttpPost]方法? (Xamarin.form + Web API)(update1)

问题描述 投票:0回答:1

我正在尝试对xamarin.form进行向Web API注册管理员帐户通过在XAML中输入值并将其注册/发布到Web API来与预定义值结合。不幸的是,我仍然是Xamarin平台的初学者。

我正在为我的类对象的[[AdminAccountController.cs] >>中的使[HttpPost]方法的主体]出现问题。(更新1)

-当请求POST时成功在Postman中返回响应

-但在POSTMAN上发出POST请求后,当我在POSTMAN中按请求GET检查时未更新

POSTMAN GET REQUEST响应(成功):-

[ { "id": 1, "username": "admin1", "password": "12345678" }, { "id": 2, "username": "admin2", "password": "12345678" } ]

POSTMAN POST REQUEST响应(由@jason提供):-

{ "id": 3, "username": "admin3", "password": "12345678" }

在POSTMAN上进行POST请求后,对GET请求的预期结果(正在进行中:-

[ { "id": 1, "username": "admin1", "password": "12345678" }, { "id": 2, "username": "admin2", "password": "12345678" }, { "id": 3, "username": "admin3", "password": "12345678" } ]

AdminAccountController.cs(已更新)

using FoodWebApi.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace FoodWebApi.Controllers { public class AdminAccountController : ApiController { List<Admin> admins = new List<Admin>() { new Admin { id=1, username="admin1", password="12345678" }, new Admin { id=2, username="admin2", password="12345678" } }; //http://localhost:53287/api/AdminAccount public IEnumerable<Admin> GetAll() { return admins; } //http://localhost:53287/api/AdminAccount/1 public IHttpActionResult GetById(int id) { var admin = admins.FirstOrDefault(x => x.id == id); if (admin == null) { return NotFound(); } return Ok(admin); } [HttpPost] public Admin PostNewAdmin(Admin admin) { // add the new admin to your list admins.Add(admin); // return to the caller return admin; } } }

Admin.cs

namespace FoodWebApi.Models { public class Admin { public int id { set; get; } public string username { set; get; } public string password { set; get; } } }

我正在尝试通过xamarin.form在Web API中注册管理员帐户,并通过在XAML中输入值并将其注册/发布到Web API来与预定义值结合。不幸的是,我是...
c# asp.net-web-api visual-studio-2015 http-post postman
1个回答
0
投票
首先,使用列表而不是数组,这很容易
© www.soinside.com 2019 - 2024. All rights reserved.