MVC 4 Web API区域404错误

时间:2012-09-06 00:00:03

标签: asp.net asp.net-mvc

我遇到的问题让我疯狂。

我有一个MVC 4 WebAPI应用程序,它定义了几个区域。

我的工作区发送控制器(SendController.cs)的定义如下:

namespace TargetAPI.Areas.Jobs.Controllers
{
    public class SendController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage Index(SendRequest req)
        {
            try
            {
            //blah blah
            }
            catch (Exception ex)
            {
            //blah blah
            }
        }
    }
}

我的工作区域注册(JobsAreaRegistration.cs)定义如下:

namespace TargetAPI.Areas.Jobs
{
    public class JobsAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Jobs";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Jobs_long",
                "Jobs/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new[] { "TargetAPI.Areas.Jobs.Controllers" }
            );
        }
    }
}

我的RouteConfig.cs说:

namespace TargetAPI
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                 name: "Default",
                 url: "{controller}/{action}/{id}",
                 defaults: new { controller = "Home", 
                     action = "Index", id= UrlParameter.Optional },
                 namespaces: new string[] { "TargetAPI.Controllers" }
            );
        }
    }
}

当我运行路由调试器时,我得到: My Route Debug http://imagestore2.boomerang.com/img/temp/routedebug.jpg

但是当我尝试发布到“作业/发送”URL时,我得到:

未找到路径'/ Jobs / Send'的控制器或未实现IController。

我已经尝试过如此多的迭代和组合,我的头脑正在旋转。有什么想法吗?

谢谢!

3 个答案:

答案 0 :(得分:10)

原来,WebAPI不处理区域!想象一下我的惊讶。所以我找到了一篇很棒的帖子http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/。现在我正在前进。

答案 1 :(得分:1)

除了不支持区域(因为MapHTTPRoute没有命名空间支持),API控制器必须使用MapHttpRoute,而不是像本例中的MapRoute(删除区域后):

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

    }

注意缺少{action},Method不是Actions,put取自HTTP请求:Get,Head等......

答案 2 :(得分:0)

我有同样的问题,解决方案很简单:我忘了添加文件_ViewStart.cshtml_Layout.cshtml,可以帮助你