Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net core Cleanest way to return View or Json/XML

In asp.net core I would like to set up my API controller to do the following:

by default return View(model);

/api/id.json to return model; as json

/api/id.xml to return model; as xml

The second two can be achieved by using the [FormatFilter] see here

[FormatFilter]
public class ProductsController
{
    [Route("[controller]/[action]/{id}.{format?}")]
    public Product GetById(int id)

However this requires the method to return an object and not a View(object). Is there anyway to cleanly support also returning Views?

like image 661
GreyCloud Avatar asked Dec 30 '25 03:12

GreyCloud


1 Answers

You cannot do both in the same action. However, you can factor out the common functionality into a private method and then implement two actions with minimal code duplication:

[Route("[controller]")]
[FormatFilter]
public class ProductsController : Controller
{
    private Product GetByIdCore(int id)
    {
        // common code here, return product
    }

    [HttpGet("[action]/{id}")]
    [ActionName("GetById")]
    public IActionResult GetByIdView(int id) => View(GetByIdCore(id));

    [HttpGet("[action]/{id}.{format}")]
    public Product GetById(int id) => GetByIdCore(id);
}

It's necessary to use different action names here, because the method signatures cannot differ merely on return type. However, the [ActionName] attribute can be used as above to make them appear to have the same name for the purposes of URL generation and such.

like image 90
Chris Pratt Avatar answered Jan 01 '26 16:01

Chris Pratt