gpt4 book ai didi

c# - CreatedAtRoute路由到不同的 Controller

转载 作者:IT王子 更新时间:2023-10-29 04:01:54 25 4
gpt4 key购买 nike

我正在使用属性路由创建一个新的 webapi 来创建一个嵌套路由:

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

但是我想返回一个没有嵌套的路由,即:

/api/Messages/{id}

在消息 Controller 上定义。然而,上面的 CreatedAtRoute 调用并没有解析这个路由而是抛出。我做错了什么,或者它不支持路由到不同的 api Controller ?注意我尝试访问的路由不是属性路由,只是默认路由。

异常(exception)情况是:

Message: "An error has occurred." ExceptionMessage: "UrlHelper.Link must not return null." ExceptionType: "System.InvalidOperationException" StackTrace: " at System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult1.Execute() at System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult1.ExecuteAsync(CancellationToken cancellationToken) at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"

如果它不支持此功能,返回 201 的规范方法是什么?我能否以重构安全的方式执行此操作?

最佳答案

哦,亲爱的,这可能是回答我自己的问题的新记录。

return CreatedAtRoute("DefaultApi", new { controller = "messages", id = message.Id }, message);

成功了。即明确指定 Controller 。我通过查看异常与 UrlHelper 相关并阅读其文档来解决这个问题...

关于c# - CreatedAtRoute路由到不同的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417559/

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