具有表单数据的邮递员不支持媒体类型

Unsupported Media Type on postman with form-data

我在 post 上尝试 post 表单数据时遇到问题。当我使用 Raw JSON 但不使用 form-data.I 使用 .net core 创建了一个 web api 并且我正在使用 Mongodb.

时它有效

这是错误:

这是我的控制器(我在 .Net 核心上并使用 Mongodb 作为数据库):

namespace CRUD_App.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _env;

        public EmployeeController(IConfiguration configuration, IWebHostEnvironment env)
        {
            this._configuration = configuration;
            this._env = env;
        }


        [HttpGet]
        public IActionResult Get()
        {
            MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));

            var dbList = dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").AsQueryable();

            return Json(dbList);
        }

        [HttpPost]

        public IActionResult Post(Employee emp)
        {
            MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));

            int LastEmployeeId = dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").AsQueryable().Count();

            emp.EmployeeId = LastEmployeeId + 1;

            dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").InsertOne(emp);

            return Json("Employee Added Successfully");
        }

        [HttpPut]
        public IActionResult Put(Employee emp)
        {
            MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));

            var filter = Builders<Employee>.Filter.Eq("EmployeeId", emp.EmployeeId);

            var update = Builders<Employee>.Update.Set("EmployeeName", emp.EmployeeName)
                                                  .Set("Department", emp.Department)
                                                  .Set("DateOfJoining", emp.DateOfJoining)
                                                  .Set("PhotoFileName", emp.PhotoFileName);

            dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").UpdateOne(filter, update);

            return Json("Employee Updated Successfully");

        }

        [HttpDelete]
        public IActionResult Delete(int id)
        {
            MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));

            var filter = Builders<Employee>.Filter.Eq("EmployeeId", id);

            dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").DeleteOne(filter);

            return Json("Employee Deleted Successfully");
        }

这种方式支持表单数据吗?

由于您使用的是 asp.net 核心,因此您可以使用 [FromForm] 属性

   public IActionResult Post([FromForm] Employee emp)

有关详细信息,请参阅 docs

对于使用 ASP WebApi 的人,您必须改为从 HttpContext.Current.Request.Form 阅读它。