【发布时间】:2019-01-20 15:53:31
【问题描述】:
我在 c# 中使用 web api 2 创建了一个控制器。
我的控制器方法是一个帖子并且成功完成,返回一个 201
但是当客户端收到响应时,返回一个500内部服务器错误。
谁能告诉我为什么会这样?
我以为一旦控制器返回一个值,请求就完成了,显然不是这样。
[HttpPost]
[Route("PostProperty/{agentId}")]
public async Task<IActionResult> PostProperty(int agentId, [FromBody]CreatePropertyRequestDto value)
{
string result = await _mediator.Send(new NewPropertyRequest() { NewProperty = value, AgentId = agentId });
var c = CreatedAtRoute("getproperties", new { agentId, propertyIds = result }, result);
return c;
}
如果我查看输出窗口,我可以看到 500 被抛出,但我仍然不知道在哪里或为什么。请帮忙
Application Insights Telemetry (unconfigured): {
"name": "Microsoft.ApplicationInsights.Dev.Request",
"time": "2018-08-13T20:51:39.9717971Z",
"tags": {
"ai.operation.name": "POST Properties/PostProperty [agentId]",
"ai.cloud.roleInstance": "DESKTOP-DM70VVS",
"ai.location.ip": "127.0.0.1",
"ai.application.ver": "1.0.0.0",
"ai.operation.id": "4d86444a-4e214be6ea456695",
"ai.internal.nodeName": "DESKTOP-DM70VVS",
"ai.internal.sdkVersion": "aspnet5c:2.1.1"
},
"data": {
"baseType": "RequestData",
"baseData": {
"ver": 2,
"id": "|4d86444a-4e214be6ea456695.",
"name": "POST Properties/PostProperty [agentId]",
"duration": "00:00:02.7187869",
"success": false,
"responseCode": "500",
"url": "http://localhost:63103/api/properties/PostProperty/1",
"properties": {
"httpMethod": "POST",
"AspNetCoreEnvironment": "Development",
"DeveloperMode": "true"
}
}
}
}
编辑:
如果我返回 OK(result),则返回 200。所以我现在可以确认CreatedAtRoute() 是罪魁祸首。我在 Startup.cs 中启用了app.UseDeveloperExceptionPage(); 并向我展示了一条有用的消息
InvalidOperationException:没有路由与提供的值匹配。
阅读this线程我可以看到我必须匹配我所说的创建项目的操作的参数。
更新的帖子操作
[HttpPost]
[Route("PostProperty/{agentId}")]
public async Task<IActionResult> PostProperty(int agentId, [FromBody]CreatePropertyRequestDto value)
{
string result = await _mediator.Send(new NewPropertyRequest() { NewProperty = value, AgentId = agentId });
return CreatedAtRoute($"GetProperty", new { agentId = agentId, propertyId = result });
}
上面引用的动作
[HttpGet]
[Route("GetProperty/{agentId}/{propertyId}")]
public async Task<IActionResult> GetProperty(int agentId, string propertyId)
{
if (agentId <= 0 || propertyId == null)
{
return BadRequest("agentId or propertyId was invalid. agentId must be a valid id and propertyId cannot be null");
}
IEnumerable<PropertyDto> properties = await GetPropertiesRequest(agentId, new List<string>(){ propertyId });
PropertyDto property = properties.FirstOrDefault();
if (property == null)
{
return NotFound();
}
return Ok(property);
}
即使更新了我的帖子操作,我仍然会收到
InvalidOperationException:没有路由与提供的值匹配。
下面也返回同样的异常
CreatedAtRoute(routeName: "GetProperty", routeValues: new { agentId = agentId, propertyId = result }, value: result);
【问题讨论】:
-
使用异常过滤器查看异常详情。如果我不得不猜测当结果被序列化为客户端的 json(或其他)时会发生这种情况。示例:如果您有一个包含逻辑的可序列化属性,其中逻辑会引发异常。另一个示例是,如果您有一个依赖于在结果序列化时释放的结果的 EF 上下文,则会引发异常。
-
另一个答案可能是结果是 201,但重新路由到结果导致 500。请检查浏览器的网络选项卡以确保。
-
这是this post on CreatedAtRoute() 中涉及的问题的副本。长话短说,你调用了错误的
CreateAtRoute方法。如果您指的是包含参数的路由,那么您应该调用三参数版本。
标签: asp.net-web-api2