【问题标题】:WebApi Areas not found未找到 WebApi 区域
【发布时间】:2012-10-30 05:04:23
【问题描述】:

我有一个 WebApi 项目,我正在尝试向它添加一个区域。

将新区域添加到 webapi 项目与 mvc4 应用程序时,是否需要做一些不同的事情?

我有一个简单的区域注册,比如

 public class MobileAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Mobile";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Mobile_default",
            "Mobile/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }

        );
    }
}

类似的控制器

  public class BusinessDetailsController : BaseController
{
    public string Index()
    {
        return "hello world";
    }
    public HttpResponseMessage Get()
    {
        var data = new List<string> {"Store 1", "Store 2", "Store 3"};
        return Request.CreateResponse(HttpStatusCode.OK, data);
    }
}

但是我永远无法访问 api。我是在做一些愚蠢的事情,还是需要对 webapi 进行额外的操作?

【问题讨论】:

    标签: c#-4.0 asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您的代码为 Area 注册了 MVC 路由,而不是 Web API 路由。

    为此,请使用 MapHttpRoute 扩展方法(您需要为 System.Web.Http 添加 using 语句)。

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.Routes.MapHttpRoute(
                name: "AdminApi",
                routeTemplate: "admin/api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    

    但是,ASP.NET Web API 中并不真正支持区域 OOTB,如果您有两个具有相同名称的控制器(无论它们是否位于不同的区域),您会遇到异常。

    要支持这种情况,您需要更改选择控制器的方式。你会发现一篇文章介绍了如何做到这一点here

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2012-06-19
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多