AndreaNobili
AndreaNobili

Reputation: 42957

Some clarification about how a controller handle an HTTP Request in C#?

I am absolutly new in C# and I am not very into MVC (I came from Java)

I have the following doubts:

I have a controller package\folder (I don't know the propper name in Visual Studio) named Controllers that contains the controllors that handle the incoming HTTP Request.

So inside this folder I have the TestController.cs class that is something like this:

namespace MyWebApplication.Controllers
{
    public class AndreaController : MyBaseController
    {
        // Manager che effettua la connessione ed ottiene i dati da visualizzare nella view:
        private MaliciousCodeManager manager = new MaliciousCodeManager("DefaultConnection");


        //
        // GET: /Test/

        /* Method that handle the HTTP REQUEST toward /Test/index
         * 
         */
        public ActionResult Index(DataModel.MaliciousCode.SearchMalicious model)
        {

            Debug.WriteLine("*** FILTRI DI RICERCA ***");
            ...................................................
            ...................................................
            ...................................................
            DO SOME STUFF
            ...................................................
            ...................................................
            ...................................................
        }
}

So, it seems to me to understand that this controller handle the request toward the /Test/ path

and so the Index() method handle the request toward /Test/index I think that this is pretty clear for me

Now my doubt is related the parameter passed to my Index method:

public ActionResult Index(DataModel.MaliciousCode.SearchMalicious model)

So the input paramether of this method is a DataModel.MaliciousCode.SearchMalicious model object.

When I execute the code in debugging mode it seems to me that, before callin the Index() method to handle the HTTP Request, it create a SearchMalicious malicious object to pass as parameter

So my doubt is: is it automatically created from the framework? Or what? What am I missing?

Tnx Andrea

Upvotes: 4

Views: 706

Answers (3)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

Actually only controller type names are important in request routing. Probably someone renamed the type but forget to rename the file. By looking at your code, that Index method will answer to http://example.org/Andrea and http://example.org/Andrea/Index URLs. Index is the default action name in default route.

If you look at your route configuration(should be in App_Start/RouteConfig.cs or Global.asax.cs) you will see the default route registration.

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

This tells ASP.NET MVC that the first segment of the URL specify the controller type and second segment tells the action method name. Action methods are the public methods in controllers that can be called from a URL according to these rules. Their return type is usually ActionResult. Controllers are the types that provide a logical container for the action methods.

Model binding in ASP.NET tries to get the values from URL segments, querystring and posted form values. Notice the last segment in default route: it tells ASP.NET MVC to create a route value named id from the third segment of the URL when provided. So when I make a request to http://example.org/Home/Index/3, I can get value 3 binded to my parameter value in my action method.

public class HomeController : MyBaseController
{
    public ActionResult Index(int id)
    {
        //id is 3
    }
}

In complex model types (such as yours) binding will look for each property value like above. Here's an example SearchMalicious type:

public class SearchMalicious 
{
    public string Keyword { get; set; }
    public string OrderBy { get; set; }
}

When you make a request to http://example.org/Andrea?keyword=abc&orderby=def, model binding will create SearchMalicious instance and fill those properties using querystring values. Also this model may be populated from the form fields in a POST request.

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Yes, your model is bound automatically. Passing a parameter to the method tells MVC that you want model binding. If you don't want model binding, then you pass an empty parameter. If you want to control how this is done, you would create a custom model binder and add it to the model binders list in the global.asax.

As a side note, you're making a lot of assumptions. Index is not necessarily the default action, it depends on how your routing is setup. The path /Test isn't necessarily what's used either, but it would be correct in the default routing condition.

Upvotes: 2

Kelly Robins
Kelly Robins

Reputation: 7288

In this scenario you are specifying the type expected by index... The object is created and then the users post values or querystring parameters are simply mapped on to it. The only requirement is that the type have a parameter-less constructor defined so the framework can create it.

In this scenario the user has no control over the type being created, only the values being mapped on to it. So yes, theoretically if you had a class defined with malicious code in the constructor you could call it that way - but that is on the developer not the end user.

What you do have to be careful with on model binding is that the framework does not know what values are supposed to be mapped. So if you show a page that has a model type of user and allows someone to update their email, they could theoretically overwrite their discount assuming it was on the same object and they knew the property name.

Upvotes: 2

Related Questions