0

Apologies if this is answered elsewhere; the only search results turned up PHP-based answers.

TL;DR - Can ASP.NET API/MVC model classes be declared inside a controller class, and are there any gotcha's when doing this?

I have many controllers that accept multiple parameters. Based on this answer, and Mike Wasson's blog, the general consensus seems to be that a complex-type parameter is best, e.g.

public class MyController : ApiController 
{
    [HttpPost]
    public HttpResponseMessage Post([FromBody] MyModel ModelParam)
    {
       // do something with ModelParam.Param1, ModelParam.Param2, etc...
    }
}

I have always put classes in the Models folder of the application, but I'm finding that my models are only being used once per controller, so I end up with as many models as I have controllers.

Perhaps I'm doing something wrong right there, but could each model live inside the controller, so the relevant logic is together? For example...

public class MyController : ApiController 
{
    public class MyModel
    {
        public string Param1{ get; set; }
        public DateTime Param2{ get; set; }
    }

    [HttpPost]
    public HttpResponseMessage Post([FromBody] MyModel ModelParam)
    {
       // do something with ModelParam.Param1, ModelParam.Param2, etc...
    }
}

I tried this, and it seems to compile and run okay. Previously when using webforms I got bitten badly by putting classes in pages (an intermittent error similar to "Cannot cast type "MyClass" to type "MyClass"). I am nervous as to whether there are any issues with this approach (or is it bad practice)?

Community
  • 1
  • 1
EvilDr
  • 8,943
  • 14
  • 73
  • 133
  • 2
    You can, but it's not useful. Look at Eric's answer: http://stackoverflow.com/questions/7984529/c-sharp-public-nested-classes-or-better-option – Smartis has left SO again Mar 29 '17 at 14:42
  • 4
    Sure you can... but why stop there? You could also include the view, the bootstrapping of the web framework, other controllers. Heck, why not put the whole application in a single file? You don't have to follow conventions, and while you might find this easier to work with, rest assured, others don't. C# convention says a single file for a single class. Keeping source files small makes them easier to work with. The development environment makes it easy to navigate. – spender Mar 29 '17 at 14:42
  • You can use area I guess. Or you can create folders specific to controllers in your models folder for easy maintainability. – Biswabid Mar 29 '17 at 14:44
  • That's good enough for me - thank you :-) – EvilDr Mar 29 '17 at 15:16

0 Answers0