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)?