gpt4 book ai didi

c# - 防止 Web API 方法被调用

转载 作者:太空狗 更新时间:2023-10-30 01:06:42 24 4
gpt4 key购买 nike

我正在使用 ASP.NET Web API 创建 Web API。我目前正在删除端点上的功能,以便我可以开始针对它进行开发。

我的 WebApiConfig.cs 文件如下所示:

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
name: "ActionAPI",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new { action = RouteParameter.Optional }
);

在我的 UsersController.cs 文件中,我有这些方法:

//Maps to /Users endpoint
[HttpGet]
public IEnumerable<User> GetAllUsers()
{
//Code
}

//Maps to /Users/{id} endpoint
[HttpGet]
public User GetUser(int id)
{
//Code
}

//Maps to /Users/{id}/Enrollments endpoint
[HttpGet, ActionName("Enrollments")]
public IEnumerable<Enrollment> GetUserEnrollments(int id)
{
//Code
}

//Maps to /Users/{id}/Enrollments/{id}
[HttpGet, ActionName("Enrollments")]
public IEnumerable<Enrollment> GetUserEnrollment(int userid, int id)
{
//Code
}

如何防止 /Users/GetUser 成为有效路由?

GetUser(int id) 上使用 [NonAction] 会阻止它完全工作。

编辑:这是 /Users/GetUser

的当前输出
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Multiple actions were found that match the request: Byui.ILearnAPI2.Business.Entities.User GetUser(Int32) on type Byui.ILearnAPI2.API.Controllers.UsersController System.Collections.Generic.IEnumerable`1[System.String] GetUserEnrollments(Int32) on type Byui.ILearnAPI2.API.Controllers.UsersController
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext) at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext) at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
</StackTrace>
</Error>

最佳答案

再次查看您的帖子后,我认为您没有正确看待错误。

由于您配置 Controller 的方式,存在不明确的路由。

找到多个与请求匹配的操作:

GetUser(Int32) 类型为 Byui.ILearnAPI2.API.Controllers.UsersController

GetUserEnrollments(Int32) 在 Byui.ILearnAPI2.API.Controllers.UsersController 类型上

GetUser 和 GetUserEnrollments 共享相同的路由。据我所知,如果您向它传递一个 int 或一个字符串或其他任何东西,GetUser 将无法工作,因为它不知道如何正确解析。

您可以在默认设置之前添加路由配置来解决问题。

config.Routes.MapHttpRoute(
name: "GetUsers",
routeTemplate: "api/users/{id}",
defaults: new { controller = "Users", action = "GetUser" }
);

关于c# - 防止 Web API 方法被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610664/

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