有nuget包Microsoft.AspNetCore.Mvc.WebApiCompatShim
主要目标是让从 Web api 到 core 的迁移变得更容易。它还提供了一种方法来执行基于约定的路由到您需要的操作。因此,首先安装该软件包,然后在启动时:
public void ConfigureServices(IServiceCollection services) {
// add conventions here
services.AddMvc().AddWebApiConventions();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseMvc(routes => {
// map one global route
routes.MapWebApiRoute("WebApi", "api/{controller}");
});
}
在这个小配置之后,您可以从继承您的控制器ApiController
,添加到上面的包中是为了方便从web api或原生asp.net core迁移Controller
。的例子ApiController
:
public class SomeController : ApiController {
// maps to GET /api/Some
// note - no routing attributes anywhere
public HttpResponseMessage Get() {
return new HttpResponseMessage(HttpStatusCode.OK);
}
// maps to POST /api/Some
public HttpResponseMessage Post() {
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
本机 asp.net core 控制器:
// mark with these attributes for it to work
[UseWebApiRoutes]
[UseWebApiActionConventions]
public class TestController : Controller {
// maps to GET /api/Test
// no routing attributes, but two "conventions" attributes
public IActionResult Get(string p) {
return new ObjectResult(new { Test = p });
}
}
您还可以使用以下属性标记您的基本控制器:
[UseWebApiRoutes]
[UseWebApiActionConventions]
public class BaseController : Controller {
}
public class TestController : BaseController {
// maps to GET /api/Test
// no attributes
public IActionResult Get(string p) {
return new ObjectResult(new { Test = p });
}
}
如果您不从 Web api 迁移 - 我建议使用本机Controller
. ApiController
具有不同的结构(类似于 asp.net web api ApiController),因此没有太多理由将其用于除其预期目标(从 web api 迁移)之外的任何用途。