ASP.Net HttpPost 操作中的核心 CreatedAtAction returns 201 但整个请求以 500 结尾
ASP.Net Core CreatedAtAction in HttpPost action returns 201 but entire request ends with 500
我正在关注[1] 以设置我的第一个 .NET Core WebAPI(从 "old" 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
returns 正确的对象,如我所料,状态代码为 201,在我的方法退出后,服务器以某种方式将其变成 500。我似乎无法进入其余部分管道。 Trace 给我以下错误:
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) 中的行为完全相同。其他 return 类型,200(new ObjectResult(item)
用于 GET,404 用于 NotFound()
或 204 NoContentResult()
用于 PUT 工作正常。所以它似乎是 201 的问题。任何想法?
[1] https://docs.asp.net/en/latest/tutorials/first-web-api.html
更新
根据请求发布其他详细信息:
Startup.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
201 尝试重定向到未处理的路由:
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
仍然不确定为什么,因为方法 GetById
应该根据控制器设置映射到 GetTodo
。
所以,经过一些调试,我找到了导致它的原因。事实证明,this.Url.Action("Get", "GetTodo", new { id=item.Key })
会 return null
而 500 来自 IIS 无法匹配附加到 201 的路由。
事实证明,您要么需要设置:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}");
});
或使用CreateAtRoute
.
在成功的 POST 请求中,我使用:
return StatusCode(201, oCreatedObject);
我正在关注[1] 以设置我的第一个 .NET Core WebAPI(从 "old" 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
returns 正确的对象,如我所料,状态代码为 201,在我的方法退出后,服务器以某种方式将其变成 500。我似乎无法进入其余部分管道。 Trace 给我以下错误:
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) 中的行为完全相同。其他 return 类型,200(new ObjectResult(item)
用于 GET,404 用于 NotFound()
或 204 NoContentResult()
用于 PUT 工作正常。所以它似乎是 201 的问题。任何想法?
[1] https://docs.asp.net/en/latest/tutorials/first-web-api.html
更新 根据请求发布其他详细信息:
Startup.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
201 尝试重定向到未处理的路由:
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
仍然不确定为什么,因为方法 GetById
应该根据控制器设置映射到 GetTodo
。
所以,经过一些调试,我找到了导致它的原因。事实证明,this.Url.Action("Get", "GetTodo", new { id=item.Key })
会 return null
而 500 来自 IIS 无法匹配附加到 201 的路由。
事实证明,您要么需要设置:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}");
});
或使用CreateAtRoute
.
在成功的 POST 请求中,我使用:
return StatusCode(201, oCreatedObject);