【发布时间】:2020-07-23 09:56:31
【问题描述】:
我正在尝试对 xamarin.form 进行 向 Web API 注册管理员帐户,通过在我的 XAML 中输入值与预定义的值相结合,然后注册/发布到 Web API。不幸的是,我还是 Xamarin 平台的初学者。
我面临为我的类对象在 AdminAccountController.cs 中制作 [HttpPost] 方法的主体 的问题。
(更新 1)
-Success 在请求 POST 时在 Postman 中返回响应
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"
}
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; }
}
}
【问题讨论】:
-
PostNewAdmin 应该做什么?根据您的代码,我假设它只会将从客户端收到的
admin对象添加到admins数组中。 -
@Jason 如何添加管理对象,我需要返回什么?我知道这是一个愚蠢的问题,但它让我整天都在挣扎。
-
我需要一个简单的例子在[HttpPost]方法中添加和返回对象,方便我学习。我已经引用了许多站点作为示例,但它不符合我的要求,即在 [HttpPost] 方法中返回一个对象。如果有任何符合要求的参考资料,您也可以在这里帮我附上。非常感谢您的帮助。
标签: c# asp.net-web-api visual-studio-2015 http-post postman