WebAPI2和MVC5路由配置 [英] WebAPI2 and MVC5 route config

查看:307
本文介绍了WebAPI2和MVC5路由配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个运行良好的C#ASP.net MVC5 Internet应用程序,并且可以使用Person模型执行CRUD操作.

I have coded a C# ASP.net MVC5 internet application that works well and I can do CRUD operations using a Person model.

我添加了一个使用实体框架的WebAPI2控制器,但是在尝试浏览到任何WebAPI控制器方法时遇到错误.

I have added a WebAPI2 controller that uses the entity framework but am getting errors when trying to browse to any of the WebAPI controller methods.

WebAPI2控制器称为PersonAPIController. Getpeople方法在该方法上方具有// GET api/PersonAPI注释,但是浏览该方法时,出现此错误:

The WebAPI2 controller is called PersonAPIController. The Getpeople method has the // GET api/PersonAPI comment above the method, yet when browsing to this method, I am getting this error:

找不到资源.

The resource cannot be found.

这是路由问题吗?

我有一个RouteConfigWebApiConfig.这两个配置需要合并吗?

I have a RouteConfig and a WebApiConfig. Do these two configs need to be combined?

这是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 }
    );
}

这是WebApiConfig的内容:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

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

当前,这是我的Application_Start方法:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

RouteConfig.RegisterRoutes(RouteTable.Routes)之前是否需要添加WebApiConfig.Register()行代码?

Does the WebApiConfig.Register() line of code need to be added before the RouteConfig.RegisterRoutes(RouteTable.Routes)?

如果是这样,需要将什么参数添加到WebApiConfig.Register()方法中?

If so, what is the parameter that need to be added to the WebApiConfig.Register() method?

预先感谢

编辑

这是要使用的确切代码:

Here is the exact code to use:

GlobalConfiguration.Configure(WebApiConfig.Register);

推荐答案

确保在RegisterRoutes(RouteCollection routes)之前调用Register(HttpConfiguration config).顺序很重要.

Make sure that to call Register(HttpConfiguration config) before RegisterRoutes(RouteCollection routes). The sequence matters.

这篇关于WebAPI2和MVC5路由配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆