Samuel Tambunan
Samuel Tambunan

Reputation: 345

Should action methods in an MVC controller, not a WEBAPI, return ActionResult only?

What are the best practices in terms of the return type of an action method of a controller?

I have an action method that saves data and returns the ID generated. What are the differences and benefits of returning ActionResult over an int?

e.g.

public ActionResult SaveValue(Payment model) {
     // Save stuff
     return this.Json(id);
}

over

public int SaveValue(Payment model) {
     // Save stuff
     return id;
}

If I'm returning an object, say the Payment model, I will return it as a json and let the Json() method convert it properly. However, with simple values, would it be correct to return the type itself and not an ActionResult?

Upvotes: 1

Views: 609

Answers (2)

Win
Win

Reputation: 62260

In your scenario, they both are essentially the same - both return a number.

However, it's worth noting that Content-Type in response headers are different.

Former (Json)

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRBcmNoaXZlXERlbW9NdmNcRGVtb012Y1xIb21lXFNhdmVWYWx1ZQ==?=
X-Powered-By: ASP.NET
Date: Wed, 19 Oct 2016 23:51:29 GMT
Content-Length: 1

Later (int)

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRBcmNoaXZlXERlbW9NdmNcRGVtb012Y1xIb21lXFNhdmVWYWx1ZTI=?=
X-Powered-By: ASP.NET
Date: Wed, 19 Oct 2016 23:51:51 GMT
Content-Length: 1

Upvotes: 2

Nkosi
Nkosi

Reputation: 247153

The following excerpts were taken from this documentation.

Controllers, Actions, and Action Results

Now while the documentation is targeted to dot net core the principle is transferable

Actions can return anything, but frequently will return an instance of IActionResult (or Task<IActionResult> for async methods) that produces a response. The action method is responsible for choosing what kind of response; the action result does the responding.

...

In addition to the methods above, an action can also simply return an object. In this case, the object will be formatted based on the client’s request.

In that case it doesn't really matter as the framework should handle the result based on the request.

The common practice is to have the return type as the abstract ActionResult. You could just as easily return the concrete implementation if preferred.

Upvotes: 0

Related Questions