代码之家  ›  专栏  ›  技术社区  ›  Vy Do

ASP。NET Core 5 Web API,返回后CreateDataAction错误

  •  0
  • Vy Do  · 技术社区  · 6 年前

    我正在使用。NET 5.0.100版-预览版。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 . . .
    

    ame

    0 回复  |  直到 6 年前
        1
  •  0
  •   Yiyi You    6 年前

    Kirk Larkin 第一个参数是action name,可以参考 this 下面是一个演示:

    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);

    推荐文章