问题描述
我正在创建一个新的 webapi,使用属性路由来创建嵌套路由,如下所示:
I'm creating a new webapi using attribute routing to create a nested route as so:
// PUT: api/Channels/5/Messages
[ResponseType(typeof(void))]
[Route("api/channels/{id}/messages")]
public async Task<IHttpActionResult> PostChannelMessage(int id, Message message)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != message.ChannelId)
{
return BadRequest();
}
db.Messages.Add(message);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = message.Id }, message);
}
但是我想返回一个没有嵌套的路由,即:
I however want to return a route that isn't nested i.e.:
/api/Messages/{id}
在消息控制器上定义.然而,上面的 CreatedAtRoute 调用并没有解析这个路由,而是抛出了.我做错了什么,或者它不支持路由到不同的 api 控制器?不详我试图命中的路线不是属性路线,只是默认路线.
which is defined on the messages controller. However The CreatedAtRoute call above is not resolving this route and instead throwing. Have I done something wrong, or does it not support routing to different api controller? n.b. the route I am trying to hit is not an attribute route, just a default one.
例外是:
消息:发生错误."ExceptionMessage: "UrlHelper.Link 不得返回 null."异常类型:System.InvalidOperationException"StackTrace: " 在 System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult1.Execute() 在 System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult
1.ExecuteAsync(CancellationToken cancellingToken) 在 System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- 从上一个抛出异常的位置开始的堆栈跟踪结束 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- 从上一个位置开始的堆栈跟踪结束异常被抛出 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"
如果它不支持这一点,返回 201 的规范方法是什么,我可以以重构安全的方式进行吗?
If it doesn't support this, what is the canonical way to return a 201 and can I do it in a refactor safe way?
推荐答案
哦,亲爱的,这可能是回答我自己问题的新记录.
Oh dear, this may be a new record for answering my own question.
return CreatedAtRoute("DefaultApi", new { controller = "messages", id = message.Id }, message);
可以解决问题.即明确指定控制器.我通过看到异常与 UrlHelper 相关并阅读其文档来解决这个问题...
does the trick. i.e. explicitly specifying the controller. I worked this our by seeing that the exception was related to the UrlHelper and reading its docs...
这篇关于CreatedAtRoute 路由到不同的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!