Div*_*Dan 0 c#-4.0 asp.net-mvc-4 asp.net-web-api
我有一个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 }
);
}
}
Run Code Online (Sandbox Code Playgroud)
像控制器一样
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是我永远无法达到api.我做了一些愚蠢的事情,还是需要做一些关于webapi的额外步骤?
您的代码为Area注册MVC路由,而不是Web API路由.
为此,请使用MapHttpRoute扩展方法(您需要为其添加using语句System.Web.Http).
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 }
);
}
Run Code Online (Sandbox Code Playgroud)
但是,ASP.NET Web API中并不真正支持区域OOTB,如果您有两个具有相同名称的控制器(无论它们是否位于不同区域),您将获得异常.
要支持此方案,您需要更改控制器的选择方式.你会在这里找到一篇文章,介绍如何做到这一点.
| 归档时间: |
|
| 查看次数: |
1823 次 |
| 最近记录: |