首页 > 解决方案 > 继承控制器时无法让路由在 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。

任何帮助深表感谢!谢谢!

标签: c#asp.net-mvcroutesasp.net-web-api2attributerouting

解决方案


发生这种情况是因为您有 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/TestOneWeb 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")]

推荐阅读