【问题标题】:Can't make a post request in .NetCore RestApi无法在 .Net Core Rest Api 中发出发布请求
【发布时间】:2021-05-29 14:06:26
【问题描述】:

我在Meeting.cs有这个模型:

    public class Meeting
    {
        public string Id { get; set; }
        [DataType(DataType.Time)]
        public TimeSpan Start_time { get; set; }
        [DataType(DataType.Time)]
        public TimeSpan End_time { get; set; }
        [DataType(DataType.Date)]
        public DateTime Date { get; set; }
        [Required]
        [Url]
        public string Url { get; set; }
        [RegularExpression(@"^[(a-zA-Z)' '(a-zA-Z)]*$",
         ErrorMessage = "Characters are not allowed.")]
        public string Owner { get; set; }
        [RegularExpression(@"^[(a-zA-Z)' '(a-zA-Z)]*$",
         ErrorMessage = "Characters are not allowed.")]
        public string Participant { get; set; }
    }

InitialMigration.cs 中看起来像这样:

        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "meetings",
                columns: table => new
                {
                    Id = table.Column<string>(type: "text", nullable: false),
                    Start_time = table.Column<TimeSpan>(type: "interval", nullable: false),
                    End_time = table.Column<TimeSpan>(type: "interval", nullable: false),
                    Date = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
                    Url = table.Column<string>(type: "text", nullable: false),
                    Owner = table.Column<string>(type: "text", nullable: true),
                    Participant = table.Column<string>(type: "text", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_meetings", x => x.Id);
                });
        }
MeetingsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.DataAccess;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    [Route("api/Meetings")]
    public class MeetingsController : ControllerBase
    {
        private readonly IDataAccessProvider _dataAccessProvider;

        public MeetingsController(IDataAccessProvider dataAccessProvider)
        {
            _dataAccessProvider = dataAccessProvider;
        }

        [HttpGet]
        public IEnumerable<Meeting> Get()
        {
            return _dataAccessProvider.GetMeetingRecords();
        }

        [HttpPost]
        public IActionResult Create([FromBody] Meeting meet)
        {
            if (ModelState.IsValid)
            {
                Guid obj = Guid.NewGuid();
                meet.Id = obj.ToString();
                _dataAccessProvider.AddMeetingRecord(meet);
                return Ok();
            }
            return BadRequest();
        }

        [HttpGet("{id}")]
        public Meeting Details(string id)
        {
            return _dataAccessProvider.GetMeetingSingleRecord(id);
        }

        [HttpPut]
        public IActionResult Edit([FromBody] Meeting meet)
        {
            if (ModelState.IsValid)
            {
                _dataAccessProvider.UpdateMeetingRecord(meet);
                return Ok();
            }
            return BadRequest();
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteConfirmed(string id)
        {
            var data = _dataAccessProvider.GetMeetingSingleRecord(id);
            if (data == null)
            {
                return NotFound();
            }
            _dataAccessProvider.DeleteMeetingRecord(id);
            return Ok();
        }
    }
}

如何解决这个问题?

但我的 JSON 数据似乎无效,我不明白为什么。 date 可能有问题?我应该用什么格式写时间和日期?

但我的 JSON 数据似乎无效,我不明白为什么。 date 可能有问题?我应该用什么格式写时间和日期?

【问题讨论】:

  • 请显示您的控制器操作。
  • 现在我需要查看 _dataAccessProvider.AddMeetingRecord(meet);
  • @Sergey, public void AddMeetingRecord(Meeting meet) { _context.meetings.Add(meet); _context.SaveChanges(); }
  • 对不起,请您从邮递员那里发布您的输入数据。我想测试一下。
  • { "date": "10/19/2021", "start_time": "19:23:23", "end_time": "20:23:23", "url": "https://blog.reedsy.com/writing-apps/#11__hemingway", "owner": "Michael KKK", "participant": "John PPP" }

标签: c# asp.net-mvc asp.net-core .net-core asp.net-core-webapi


【解决方案1】:

在我的测试中,我根本找不到任何错误,但我知道您的日期格式有问题。尝试将新属性添加到您的会议类:

[NotMapped]
public string StrDate { get; set; }

并使用此名称作为您的字符串日期:

{ "strdate": "10/19/2021", "start_time": "19:23:23","end_time": "20:23:23", "url": "https://blog.reedsy.com/writing-apps/#11__hemingway", "owner": "Michael KKK", "participant": "John PPP" }

将您的数据洞察转化为您的行动:

         [HttpPost]
        public IActionResult Create([FromBody] Meeting meet)
        {
        
            if (ModelState.IsValid)
            {
                var arrDate = meet.StrDate.Split('/');
                Guid obj = Guid.NewGuid();
                meet.Date = new DateTime(year: Convert.ToInt32(arrDate[2]), month: Convert.ToInt32(arrDate[0]), day: Convert.ToInt32( arrDate[1]));
                meet.Id = obj.ToString();
                
                return Ok(meet);
            }
            return BadRequest();
        }

【讨论】:

  • 我收到一个错误Build failed. Use dotnet build to see the errors,在输入 dotnet build 后我收到了这个error CS1061: 'Meeting' does not contain a definition for 'StrDate' and no accessible extension method 'StrDate' accepting a first argument of type 'Meeting' could be found (are you missing a using directive or an assembly reference?) [C:\Users\Мар?я\source\repos\WebApplication2\WebApplication2.csproj]
  • @Aska 你添加了公共字符串 StrDate { get;放; } 到你的会议课上?
  • 是的,我添加了,但实际上我将 public class Meeting 更改为 public class Meeting : IValidatableObject 并为 StrDate 添加了一些验证
  • public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext) { List&lt;ValidationResult&gt; results = new List&lt;ValidationResult&gt;(); DateTime temp; if (DateTime.TryParse(StrDate, out temp) == false) { results.Add(new ValidationResult("Date is wrong", new[] { "Date" })); }return results; }
  • 只是不要忘记包含 [NotMapped] 属性
猜你喜欢
  • 2021-08-05
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 2021-03-31
  • 2019-02-24
相关资源
最近更新 更多