33

In Ruby on Rails, you can generate controllers using something like the following in command line:

rails generate controller ControllerName action1 action2 ...etc

Is there something similar in the dotnetcore cli for generating controllers?

From what I can find the dotnetcore cli seems quite limited in the commands that you can do. I did find something from Microsoft's docs about extending the cli but I am not confident about how to do that for a command such as this.

UPDATE: Jan 29th 2019

@Jspy's answer is the new way of generating controllers using dotnetcore cmd since mid 2018.

UPDATE: Dec 21st 2016

Using @Sanket's answer I was able to generate controllers for my dotnetcore application. However I encountered an error

Package Microsoft.Composition 1.0.27 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.Composition 1.0.27 supports: portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
One or more packages are incompatible with .NETCoreApp,Version=v1.1.

To solve this issue I added "net451" to the framework import statement for the netcoreapp1.1 dependency.

My simple project.json file for my empty project (using @Sanket's project.json template) looked like this:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    },
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.0-*",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-*"
  },
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.1.0-preview4-final",
      "imports": [
        "portable-net45+win8"
      ]
    }
  },
  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.1.0"
        }
      },
      "imports": [
        "netcoreapp1.1",
        "net451"
      ]
    }
  }
}

After running (in terminal) $ dotnet restore I could run the following command to generate a basic controller.

dotnet aspnet-codegenerator --project . controller -name SimpleController

This generated an empty controller SimpleController.cs with the following code: (Note that my dotnet project was called ToolsAppDotNetCore)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace ToolsAppDotNetCore
{
    public class SimpleController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}
Danoram
  • 8,132
  • 12
  • 51
  • 71

2 Answers2

43

This is the new way since mid 2018

You have to install dotnet-aspnet-codegenerator.
This is now done globally and not through a Nuget package:

PowerShell:

dotnet tool install --global dotnet-aspnet-codegenerator

Then this is how you create a REST-Controller from an existing EF Model in PowerShell:

dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" controller -name MyDemoModelController -api -m My.Namespace.Models.MyDemoModel -dc MyDemoDbContext -outDir Controllers -namespace My.Namespace.Controllers

Some helpful calls

Show available generators (-p... -h):

dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" -h

Show available options of the "controller" generator (-p... controller -h):

dotnet-aspnet-codegenerator -p "C:\MyProject\MyProject.csproj" controller -h

Generate controllers for many models in a loop

This is how you would generate REST controllers for all models in a given path from a PowerShell:

Get-ChildItem "C:\MyProject\Models" -Filter *.cs | 
Foreach-Object {
    $scaffoldCmd = 
    'dotnet-aspnet-codegenerator ' + 
    '-p "C:\MyProject\MyProject.csproj" ' +
    'controller ' + 
    '-name ' + $_.BaseName + 'Controller ' +
    '-api ' + 
    '-m My.Namespace.Models.' + $_.BaseName + ' ' +
    '-dc MyDemoDbContext ' +
    '-outDir Controllers ' +
    '-namespace My.Namespace.Controllers'

    # List commands for testing:
    $scaffoldCmd

    # Excute commands (uncomment this line):
    #iex $scaffoldCmd
}
Jpsy
  • 20,077
  • 7
  • 118
  • 115
  • How can I upload external file in MVC project through powershell command ? – Siddhi Kamat Apr 14 '21 at 10:04
  • In case if anyone else was wondering how to install this, I grabbed the .NET CLI (Global) installer [here](https://www.nuget.org/packages/dotnet-aspnet-codegenerator/) and ran the PowerShell script from [this answer](https://stackoverflow.com/a/62877249/2113548). – Simple Sandman May 17 '21 at 20:37
14

If you are using Command line, you can get scaffold features with Code Generator package. To use this, first you need to include CodeGeneration packages in project.json.

"dependencies": {
  "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
    "version": "1.0.0-preview2-final",
    "type": "build"
  },
  "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
    "version": "1.0.0-preview2-final",
    "type": "build"
  }
},
"tools": {
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
  "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
  "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
    "version": "1.0.0-preview2-final",
    "imports": [
      "portable-net45+win8"
    ]
  }
}

Now you can restore the packages using dotnet restore command. Once it is completed, you can scaffold controllers and views with the following command-

dotnet aspnet-codegenerator --project . controller -name HelloController -m Author -dc WebAPIDataContext

The above command will generate controller with name HelloController in the root directory, and views for CRUD options inside Hello folder under Views folder. You can use --help commandline switch after controller parameter to get more options about controller generator.

Sanket
  • 19,295
  • 10
  • 71
  • 82
  • I'm having trouble restoring the packages to my project :/ `Package Microsoft.Composition 1.0.27 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.Composition 1.0.27 supports: portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259) One or more packages are incompatible with .NETCoreApp,Version=v1.1.` It might be worth me mentioning that I'm using Mac terminal/VS Code. – Danoram Dec 21 '16 at 06:14
  • @Danoram I never tried on Mac but worth looking into this issue - https://github.com/dotnet/corefx/issues/9788 – Sanket Dec 21 '16 at 06:32
  • @Danoram Please take a look at this one - https://stackoverflow.com/questions/40846326/the-dependency-microsoft-composition-1-0-27-does-not-support-framework-netcorea – Sanket Dec 21 '16 at 09:28
  • I fixed the issue by adding "net451" to the netcoreapp1.1 import. I'll update my question soon for this specific case. btw does `-m Author` need the model `Author` to already exist? I get errors if I include this but when I remove it it works fine – Danoram Dec 21 '16 at 09:36
  • Above command will help you create Controller with read write action using model and EF. without model or dbcontext, it will create empty controller. – Sanket Dec 21 '16 at 09:57
  • 1
    Sanket, project.json has been deprecated; your comment is outdated. I need to generate controllers for a Web API project through the command line. Can you provide instructions to do this? – Code_Steel Nov 24 '17 at 03:44