c# - 继承控制器时无法让路由在 ASP.Net Web API 2 中工作
问题描述
我试图让它在我的 ASP.Net Web API 2 应用程序中工作。你会注意到这个Controller继承了Controller。这是因为我需要返回一个视图而不是 JSON。
[RoutePrefix("api/Manage")]
public class ManageController : Controller
{
[Route("TestOne")]
public async Task<ActionResult> MyTestOne(string value1, string value2)
{
return View("");
{
}
这是我得到的错误。
<error>
<MessageDetail> No type was found that matches the controller named 'Manage'.</MessageDetail>
</Error>
我需要像这样调用管理控制器。
https://api.domain.com/api/Manage/TestOne?value1=foo&value2=bar
我的 RouteConfig 是这样配置的。
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
注意:[RoutePrefix("api/Account")] 在我的 AccountController 中工作。这是一个 API 控制器并继承 ApiBase。
任何帮助深表感谢!谢谢!
解决方案
发生这种情况是因为您有 2 个路由配置,一个用于MVC
控制器,一个用于Web API
. 在您的情况下,Web API
路线配置首先进行。Global.asax.cs
看起来像这样
//some configs
WebApiConfig.Register(GlobalConfiguration.Configuration);
//some configs
RouteConfig.RegisterRoutes(RouteTable.Routes);
你必须在Web API
路由配置中有这样的东西
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
当您请求路由时,首先应用/api/Manage/TestOne
。Web API
没有基于属性的路由适合,但请求与DefaultApi
路由完全匹配。Manage
匹配{controller}
并TestOne
转到{id}
。因此框架开始搜索名称Manage
如下的 api 控制器
public class ManageController : ApiController
但是没有这样的控制器,确实你有一个错误
{
"Message": "No HTTP resource was found that matches the request URI 'http://host/api/Manage/TestOne/?value1=foo&value2=bar'.",
"MessageDetail": "No type was found that matches the controller named 'Manage'."
}
所以我可以建议你几个可能的解决方案。
更改路由配置顺序
//some configs
RouteConfig.RegisterRoutes(RouteTable.Routes);
//some configs
WebApiConfig.Register(GlobalConfiguration.Configuration);
然后您的示例将按预期工作,但它可能会产生意外错误,因为我不知道您的应用程序中所有可能的路由。
删除DefaultApi
路线
如果您完全依赖基于属性的路由,Web API
您可以删除此配置,而不会对您的应用程序产生负面影响
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
或者只是更改前缀
如果您将前缀从更改api
为其他任何内容,它也会起作用,因为它不再匹配DefaultApi
路由
[RoutePrefix("view/Manage")]
推荐阅读
- python - OpenCV Flask 多个流不起作用
- ios - SwiftUI SignInWithAppleButton onCompletion 永远不会在 M1 Mac 上被调用
- javascript - Firebase - 使用变量作为属性获取字段
- python - 如何将动态文件名发送到 PipeLine?
- android - 可点击的 Cardview 打开另一个活动
- forms - 显示相同的值并保存在表单中
- mysql - mysql 在一个查询中进行各种分组
- html - 将 XXXL 添加到引导程序
- r - 如何最好地拆分 tibble 中的字符串并仅保留与 dplyr/R 中所需字符串匹配的项目?
- python - Python - 设置任意轮廓xy比率