簡體   English   中英

ASP.NET Core 5 Web API,POST 返回 CreatedAtAction 錯誤

[英]ASP.NET Core 5 Web API, POST return CreatedAtAction error

我正在使用 .NET 版本 5.0.100-preview.8.20417.9 。 這里有什么問題:

return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, TrustedPerson(item));

模型

using System;

#nullable disable

namespace shadow.Models
{
    public partial class TrustedPerson
    {
        public int Id { get; set; }
        public string Fullname { get; set; }
        public string AliasName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber1 { get; set; }
        public string PhoneNumber2 { get; set; }
        public string PhoneNumber3 { get; set; }
        public int? RelationshipId { get; set; }
        public string About { get; set; }
        public int? AvatarId { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Modified { get; set; }
    }
}

文件TrustedPersonController

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using shadow.Data;
using shadow.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace shadow.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class TrustedPersonController : ControllerBase
    {

        private readonly ApplicationDbContext _db; 

        public TrustedPersonController(ApplicationDbContext context) : base()
        {
            this._db = context;
        }

        /// <summary>
        /// UserId = id của người dùng chính.
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("all")]
        public ActionResult GetAllTrustedPersons(string UserId)
        {
            var list = from trustedPerson in _db.TrustedPeople
                       join userTrustedPerson in _db.UserTrustedPeople on trustedPerson.Id equals userTrustedPerson.TrustedPersonId
                       // join user in db.Users on User.Identity.Id 
                       where userTrustedPerson.UserId == UserId
                       select trustedPerson;
            return Ok(list.ToList());
        }

        [HttpPost]
        public async Task<ActionResult<TrustedPerson>> AddTrustedPersons(TrustedPerson trustedPerson)
        {
            var item = new TrustedPerson
            {
                Fullname = trustedPerson.Fullname,
                About = trustedPerson.About,
                AliasName = trustedPerson.AliasName,
                AvatarId = trustedPerson.AvatarId,
                Created = DateTime.Now,
                Email = trustedPerson.Email,
                PhoneNumber1 = trustedPerson.PhoneNumber1,
                PhoneNumber2 = trustedPerson.PhoneNumber2,
                PhoneNumber3 = trustedPerson.PhoneNumber3,
                RelationshipId = trustedPerson.RelationshipId
            };
            _db.TrustedPeople.Add(item);
            await _db.SaveChangesAsync();
            return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, TrustedPerson(item));
        }
    }

}

錯誤

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://0.0.0.0:5002
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\shadow_backend
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data, this mode should only be enabled during development.
warn: Microsoft.EntityFrameworkCore.Model.Validation[30000]
      No type was specified for the decimal column 'Id' on entity type 'Topic'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()' or specify a ValueConverter.
warn: Microsoft.EntityFrameworkCore.Model.Validation[30000]
      No type was specified for the decimal column 'PublisherId' on entity type 'Topic'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()' or specify a ValueConverter.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.InvalidOperationException: No route matches the supplied values.
         at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)
         at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

D:\shadow_backend\bin\Debug\net5.0\shadow.exe (process 13440) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

阿姆

正如Kirk Larkin所說,第一個參數是動作名稱,你可以參考這個。這是一個演示:

public class Item { 
        public int Id { get; set; }
    }
        [Route("TrustedPerson")]
        public IActionResult TrustedPerson(int id)
        {
            return Ok();
        }
        [Route("TestCreatedAtAction")]
        public IActionResult TestCreatedAtAction() {
            Item item = new Item { Id = 1 };
            return CreatedAtAction("TrustedPerson", new { id = item.Id }, item);
        }

或者你可以使用return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, item);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM