ASP.NET CoreのMVC6が2つのパターンを1つに統合したのは、私が両方の世界をサポートする必要があるためです。それはあなたが任意の標準MVCを微調整することができますことは事実だがController(および/または独自の開発ActionResultと同じように行動&動作するクラス)ApiController、非常に維持するのは難しいとテストになりますその上、持つコントローラ返すメソッドActionResult他者との混合を生のIHttpActionResultデータやシリアル化されたデータを返すことは、開発者の観点から見ると非常に混乱する可能性があります。特に、単独で作業しておらず、他の開発者にそのハイブリッドアプローチでスピードを上げる必要がある場合は特にそうです。
ASP.NET非コアWebアプリケーションの問題を最小限に抑えるためにこれまでに行った最良の方法は、Web APIパッケージをMVCベースのWebアプリケーションにインポート(および適切に構成)することです。ワールド:ControllersビューApiControllers用、データ用。
そのためには、次のことを行う必要があります。
- NuGet:
Microsoft.AspNet.WebApi.Coreとを使用して、次のWeb APIパッケージをインストールしますMicrosoft.AspNet.WebApi.WebHost。
- 1つ以上のApiControllersを
/Controllers/フォルダーに追加します。
- 次のWebApiConfig.csファイルを
/App_Config/フォルダーに追加します。
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
最後に、上記のクラスをスタートアップクラスに登録する必要があります(Startup.csまたはGlobal.asax.csOWINスタートアップテンプレートを使用しているかどうかに応じて、)。
Startup.cs
public void Configuration(IAppBuilder app)
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureAuth(app);
// ...
}
Global.asax.cs
protected void Application_Start()
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// ...
}
このアプローチとその長所と短所については、ブログに書いたこの投稿で詳しく説明しています。
ApiControllerているControllerため、新しい.NETを使用している場合は、ApiControllerについて心配する必要はありません-docs.microsoft.com/en-us/aspnet/core/tutorials/first-web- api