首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.NET核心5 Web API,POST返回CreatedAtAction错误

ASP.NET核心5 Web API,POST返回CreatedAtAction错误
EN

Stack Overflow用户
提问于 2020-09-04 18:31:32
回答 1查看 933关注 0票数 1

我使用的是.NET版本5.0.100-preview.8.20417.9。这里出了什么问题:

代码语言:javascript
运行
复制
return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, TrustedPerson(item));

模型

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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));
        }
    }

}

错误

代码语言:javascript
运行
复制
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 . . .

EN

回答 1

Stack Overflow用户

发布于 2020-09-07 11:03:44

正如Kirk Larkin所说,第一个参数是动作名称,你可以参考this.Here是一个演示工作:

代码语言:javascript
运行
复制
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);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63739427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档