我有一个带有两个控制器的MVC应用程序,一个用作WebAPiApplication
,第二个用作常规MvCApplication
。我已经以某种方式配置了只能访问API的路由。
您能以我可以访问两个控制器的方式帮助我配置它吗?
我可以通过指向DefaultController
来访问API的http://localhost/api/data
。但是,我无法访问MvcApplication Index方法。我的期望是通过poinitng访问http://localhost/Notification
来访问它,但出现错误404!
这是我的Controllers C#源代码:
//DefaultController.cs
namespace MyApp.Controllers
{
[RoutePrefix("api")]
public class DefaultController : ApiController
{
[Route("data")]
[AcceptVerbs("GET")]
public HttpResponseMessage GetMeData()
{
XYZ...
}
}
}
//NotificationController.cs
namespace MyApp.Controllers
{
public class NotificationController : Controller
{
public ActionResult Index()
{
return this.Jsonp(Rep.All());
}
}
}
这里是我如何设置到这两个控制器的路由:
//Global.asax.cs
namespace MyApp
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Notification", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Notification", action = "Index" } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
//WebApiConfig.cs
namespace MyApp
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
最佳答案
如@ChimaOsuji的评论中所述,
您已经创建了两个应用程序WebApiApplication
和MvcApplication
。
您只需要一个即可在其中注册MVC和API的路由
控制器。
Global.asax.cs
namespace MyApp
{
public class WebApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Notification", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Notification", action = "Index" } // Parameter defaults
);
}
protected void Application_Start()
{
//Web api config
GlobalConfiguration.Configure(WebApiConfig.Register);
//MVC config
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}