C# ASP.NET Web API post方法参数始终为空
这是我的模特课:C# ASP.NET Web API post方法参数始终为空,c#,asp.net,web,http-post,asp.net-web-api2,C#,Asp.net,Web,Http Post,Asp.net Web Api2,这是我的模特课: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Test.Models { public class User { public int Id { get; set; } public string Name { get; set; } //public DateTime
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
//public DateTime startTime { get; set; }
//public DateTime endTime { get; set; }
//public int Age { get; set; }
//public string Adress { get; set; }
}
}
这是我的控制器类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Test.DBA;
using Test.Models;
namespace Test.Controllers
{
public class UserAPIController : ApiController
{
ApiDbContext dbContext = null;
public UserAPIController()
{
dbContext = new ApiDbContext();
}
[HttpPost]
public IHttpActionResult InsertUser(User user)
{
dbContext.Users.Add(user);
dbContext.SaveChangesAsync();
return Ok(user.Name);
}
public IEnumerable<User> GetAllUser()
{
var list = dbContext.Users.ToList();
return list;
}
[HttpPost]
public IHttpActionResult DeleteUser(User user)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
return Ok(user.Name);
}
[HttpGet]
public IHttpActionResult ViewUser(int id)
{
var student = dbContext.Users.Find(id);
return Ok(student);
}
[HttpPost]
public IHttpActionResult UpdateUser(User user)
{
User std = dbContext.Users.Find(user.Id);
std.Name = user.Name;
//std.startTime = user.startTime;
//std.endTime = user.endTime;
//std.Age = user.Age;
//std.Adress = user.Adress;
dbContext.Entry(std).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChangesAsync();
return Ok();
}
}
}
get方法可以工作,但是当我调试post方法时,参数总是空的
编辑1:路由:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
尝试使用
[FromBody]
装饰您的参数:
public IHttpActionResult DeleteUser([FromBody]User user)
尝试将以下请求标头添加到邮递员:
Content-Type: application/json
您使用的路由类型是什么?我编辑了原始帖子。您使用什么作为接受和内容类型的标题?@foobar抱歉,我不知道您在问什么,但如果您询问帖子请求,我不会使用任何标题,我也不知道接受什么is@Saizaku,是的,这些是请求头。我想邮递员会在幕后为你保管这些邮件。但是,这有时会导致问题。不要忘记,然后应该在Body选项卡中选择“raw”单选按钮。谢谢,它成功了,我花了几天时间试图让它成功,非常感谢@toadfladkx我已经选择了单选按钮,只是缺少标题
Content-Type: application/json