gpt4 book ai didi

HttpPost 操作中的 ASP.Net Core CreatedAtAction 返回 201,但整个请求以 500 结束

转载 作者:行者123 更新时间:2023-12-04 19:40:28 24 4
gpt4 key购买 nike

我正在关注 [1] 设置我的第一个 .NET Core WebAPI(从“旧”WebAPI 移动)。当我执行 HttpPost 操作时,如教程中所示:

[HttpPost]
public IActionResult Create([FromBody] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
TodoItems.Add(item);
return CreatedAtAction("GetTodo", new { id = item.Key }, item);
}

退出 Controller 后,我收到 HttpError 500。 CreatedAtAction如我所料,返回带有状态代码 201 的正确对象,并且在我的方法退出后,服务器以某种方式将其转换为 500。我似乎无法进入管道的其余部分。跟踪给了我以下错误:
81.  -GENERAL_REQUEST_ENTITY 
82. -NOTIFY_MODULE_COMPLETION
83. -MODULE_SET_RESPONSE_ERROR_STATUS [Warning] 171ms

ModuleName AspNetCoreModule
Notification EXECUTE_REQUEST_HANDLER
HttpStatus 500
HttpReason Internal Server Error
HttpSubStatus 0
ErrorCode The operation completed successfully. (0x0)
ConfigExceptionInfo

一切(Program.cs、Startup.cs)都完全按照 [1] 中的设置。在 IISExpress (VS2015 Update 3) 和 IIS7.5 (Windows 7) 中的行为完全相同。其他返回类型,200(使用 new ObjectResult(item) 用于 GET,404 用于 NotFound() 或 204 NoContentResult() 用于 PUT 工作正常。所以看起来 201 不知何故有问题。有什么想法吗?

[1] https://docs.asp.net/en/latest/tutorials/first-web-api.html

更新
根据请求发布其他详细信息:

启动.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FirstWebApi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace FirstWebApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddLogging();
services.AddSingleton<ITodoRepository, TodoRepository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseDeveloperExceptionPage();
app.UseStatusCodePages();

app.UseMvc();
}
}
}

TodoController.cs:
using System.Collections.Generic;
using FirstWebApi.Models;
using Microsoft.AspNetCore.Mvc;

namespace FirstWebApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
public TodoController(ITodoRepository todoItems)
{
TodoItems = todoItems;
}
public ITodoRepository TodoItems { get; set; }

public IEnumerable<TodoItem> GetAll()
{
return TodoItems.GetAll();
}

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}

[HttpPost]
public IActionResult Create([FromBody] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
TodoItems.Add(item);
return CreatedAtAction("GetTodo", new { id = item.Key }, item);
}

[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody] TodoItem item)
{
if (item == null || item.Key != id)
{
return BadRequest();
}

var todo = TodoItems.Find(id);
if (todo == null)
{
return NotFound();
}

TodoItems.Update(item);
return new NoContentResult();
}

[HttpDelete("{id}")]
public void Delete(string id)
{
TodoItems.Remove(id);
}
}
}

更新 2

结果, CreateAtAction with 201 尝试重定向到未处理的路由:
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)

仍然不知道为什么,因为方法 GetById应该映射到 GetTodo每个 Controller 设置。

最佳答案

因此,经过一些调试后,我找到了导致它的原因。原来this.Url.Action("Get", "GetTodo", new { id=item.Key })会返回 null并且 500 来自于 IIS 无法匹配附加到 201 的路由这一事实。

事实证明,您要么需要设置:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}");
});

或使用 CreateAtRoute .

关于HttpPost 操作中的 ASP.Net Core CreatedAtAction 返回 201,但整个请求以 500 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com