ApiController无法在C#

时间:2020-02-05 10:02:56

标签: c# asp.net api

我刚刚开始学习c#,ASP.net,并且遇到了这个问题。这是代码。我在模型文件夹中有一个名为Role.cs的模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace xrakFRS.Models {
   public class Role {
     [Key]
     public int ID { get; set; }
     public string Rolename { get; set; }
     public string Description { get; set; }
  }

}

这是我的RolesController

   using xrakFRS.Data;
   using xrakFRS.Models;
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net;
   using System.Net.Http;
   using System.Web.Http;
   using System.Web.Http.Cors;

   namespace xrakFRS.Controllers {

  [EnableCors("*", "*", "*"), RoutePrefix("api/roles")] 
  public class RolesController : ApiController{

    [HttpGet]
    [Route("getroles")]
    public IHttpActionResult GetRoles() {
        try {
            using (var context = new AppDbContext()) {
                var entries = context.Roles.ToList();
                return Ok(entries);
            }
        } catch (Exception ex) {
            return BadRequest(ex.Message);
        }
    }

    [HttpPost]
    [Route("postrole")]
    public IHttpActionResult PostRole([FromBody] Role role) {

        if (!ModelState.IsValid) return BadRequest(ModelState);
        try {
            using (var context = new AppDbContext()) {
                context.Roles.Add(role);
                context.SaveChanges();
                return Ok("Entry was created");
            }
        } catch (Exception ex) {
            return BadRequest(ex.Message);
        }
     }

当我尝试使用邮递员调用api时,我得到了:

enter image description here

当我尝试检查断点处的变量时,会得到空值:

enter image description here

我获得“角色名称”和“描述”的空值。我不确定为什么我的数据没有绑定到控制器上。

3 个答案:

答案 0 :(得分:0)

尝试从邮递员发送raw正文

{
  "rolename": "Admin user for the application",
  "description": "Administrator"
}

答案 1 :(得分:0)

转到邮递员正文->选择原始,然后从下拉菜单json 然后进入正文并添加

{
    "roleId":1,
    "rolename":" bla bla",
    "description" : " bla bla"
}

答案 2 :(得分:0)

尝试通过邮递员使用 x-www-form-urlencoded 并删除[FromBody]属性。它将自动将变量映射到对象。代码如下:

[HttpPost]
    [Route("postrole")]
    public IHttpActionResult PostRole(Role role) {
             //Any logic here
     }

请求在邮递员中应如何显示 Postman should look like this

相关问题