Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c# - .Net Core not routing to POST Method but GET Method works

I'm training with the sample web application. For unknown reason .Net Core does not route POST requests to corresponding method. Get methods are working but POST not even being fired. POST requests return 404.

I already tried to add annotation like that but it didn't help.

Could someone pleas

[HttpPost("envelope")]

Here's the code of my controller.

namespace Receiver.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class EnvelopesController : ControllerBase
    {
        private readonly ReceiverDbContext _dbContext;
        private readonly ILogger _logger;

        public EnvelopesController(ReceiverDbContext dbContext, ILogger logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }



        /// <summary>
        /// GET (Read all) /envelopes
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<ActionResult<IEnumerator<EnvelopeDTO>>> GetAll()
        {

            _logger.LogInformation("Hello from the Get() method!");

            var envelopes = await _dbContext.Envelope.Include(e => e.Type).ToArrayAsync();
            return Ok(envelopes.Select(e => e.ToDTO()));

            
        }

        /// <summary>
        /// GET (Read) /envelope/{id}
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<EnvelopeDTO>> Get(int id)
        {
            var envelope = await _dbContext.Envelope.Include(e => e.Type).FirstOrDefaultAsync(s => s.Id == id);

            if (envelope == null)
                return NotFound();

            return Ok(envelope.ToDTO());
        }

        /// <summary>
        /// POST (Create) /envelope
        /// </summary>
        /// <param name="envelopeDto"></param>
        /// <returns></returns>
        [HttpPost("envelope")]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status409Conflict)]
        public async Task<ActionResult<EnvelopeDTO>> Create([FromBody] EnvelopeDTO envelopeDto)
        {
            _logger.LogInformation("Hello from the Post() method!");

            if (string.IsNullOrEmpty(envelopeDto.СontentX))
                return BadRequest();

            var @type = await _dbContext.EnvelopeType.FirstOrDefaultAsync(t => t.Id == envelopeDto.TypeId);
            if (@type == null)
                return NotFound();

            var @user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserName == envelopeDto.User);
            if (@user == null)
                return NotFound();

            var existingEnvelope = await _dbContext.Envelope.FindAsync(envelopeDto.СontentX);
            if (existingEnvelope != null)
                return Conflict();

            var envelopeToAdd = envelopeDto.ToModel(@type, @user);
            _dbContext.Envelope.Add(envelopeToAdd);
            await _dbContext.SaveChangesAsync();
            var updatedEnvelopeDto = envelopeToAdd.ToDTO();

            return CreatedAtAction(nameof(Get), new { Content = envelopeDto.СontentX }, updatedEnvelopeDto);
            
        }

        /// <summary>
        /// DELETE /envelope/{id}
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<EnvelopeDTO>> Delete(int id)
        {
            var envelope = await _dbContext.Envelope.FindAsync(id);
            if (envelope == null)
                return NotFound();

            _dbContext.Envelope.Remove(envelope);
            await _dbContext.SaveChangesAsync();
            return Ok(envelope.ToDTO());
        }
                
    }
    public static class EnvelopeExtensions
    {
        public static Envelope ToModel(this EnvelopeDTO envelopeDto, EnvelopeType @type, User @user)
        {
            //if (@class.Id != studentDto.ClassId) throw new NotSupportedException();
            return new Envelope
            {
                //DateTimeReceivied = DateTime.Now,
                Type = @type,
                СontentX = envelopeDto.СontentX,
                User = @user
            };
        }
        public static EnvelopeDTO ToDTO(this Envelope envelope)
        {
            return new EnvelopeDTO
            {
                //DateTimeReceivied = DateTime.Now,
                TypeId = envelope.Type.Id,
                СontentX = envelope.СontentX,
                User = envelope.User.UserName
            };
        }
    }
}

Here are the samples of POST and GET requests. enter image description here

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change

[HttpPost("envelope")]

to

[HttpPost]

The way you have it coded the POST body would be posted to the POST /envelopes/envelope endpoint, which appears to be what you don't want.

Also your comments in the other methods are misleading. For example

// DELETE /envelope/{id}

should really be

// DELETE /envelopes/{id}.

The [controller] portion of [Route("[controller]")] will be substituted with the lowercase portion of the controller name without Controller (i.e. /envelopes (plural) forms the basis for your endpoints from EnvelopesController.

In your Postman screenshots you can see that you were trying to GET from plural /envelopes (good) but post to singular /envelope, which is not defined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...