Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Web Api - Inheriting route from base controller

Is it "legal" to have a controller inherit a route from its BaseController ? It seems it's not allowed for Attribute Routing , but how about normal route registration via RouteCollection?

The reason is I currently have a bunch of controllers, each representing some kind of file converter. Each of them has a common set of methods to upload the file to be converted. These method are endpoints on each controller not just private methods. I'd like for the following routes to be valid:

/api/controller1/uploadfile
/api/controller2/uploadfile
/api/controller3/uploadfile

Can I get an example how this could be done inside a BaseController and if it's not possible, an alternative.

like image 775
parliament Avatar asked Oct 02 '22 06:10

parliament


2 Answers

Here's what works:

public abstract class BaseUploaderController : ApiController
{
    [HttpGet, Route("uploadfile")] //Needs both because HttpGet("uploadfile") currently only supported in MVC attribute routing 
    public string UploadFile() 
    {
        return "UploadFile";
    }
}


[RoutePrefix("api/values")]
public class ValuesController : BaseUploaderController
{
    [Route("{id:int}")]
    public string Get(int id)
    {
        return "value";
    }
}
like image 183
parliament Avatar answered Oct 05 '22 23:10

parliament


Are you looking to place this UploadFile action in the base controller and other controllers inheriting from them should still be able to hit UploadFile from their respective routes like you mentioned in your post? If yes, you could create an abstract base api controller and place this UploadFile action in it and your requests to the individual controllers should work as expected.

Example:

public abstract class BaseApiController : ApiController
{
    // POST /api/Values
    // POST /api/Test
    public string UploadFile()
    {
        return "UploadFile";
    }
}

public class TestController : BaseApiController
{
    // GET /api/test/10
    public string GetSingle(int id)
    {
        return "Test.GetSingle";
    }
}

public class ValuesController : BaseApiController
{
    // GET /api/values/10
    public string GetSingle(int id)
    {
        return "Values.GetSingle";
    }
}
like image 42
Kiran Avatar answered Oct 05 '22 23:10

Kiran