2

Writing with MVC in C#, I have a device that issues an HTTP request to {host}/clock. I want different devices to write to different places, so I want to enter the host as {.../company1/}, {.../company2/}. I would then have a CompanyController that would redirect requests for company1, company2, etc. without hardcoding the names of the companies.

So a request to {host}/company/company1/clock would write to company1's database. Presumably if I entered {host}/company/notacompany/, I would still want to see the value "notacompany", so I can redirect it somewhere else. How would I go about catching company1 as an address within the company controller without specifically coding a company1 action, or is this the wrong way to go about this?

1 Answer 1

3

You can use attribute routes to tell the routing engine what to do with the route parameter (company1, company2, etc...). You can use a switch and handle the notacompany in the default:

public class CompanyController : Controller {
    [Route("/[controller]/{companyId}")]
    public ActionResult Index(string companyId) {
        switch(companyId) {
            case "company1":
                //Process company1.
            case "company2":
                //Process company2.
            default:
                //Process 'notacompany' here.
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I appreciate the reply, unfortunately this doesn't solve my issue. I would still have to hard code each case for every new company I add.
How else do you expect the app to know where to redirect the request? Somewhere, you'll have to tell it what do and where to go. You don't need to hardcode the values in the switch statement. I only did that for the answer, but you can have the list of companies coming from a database, an xml fine, the config fine, etc...
Correction: (an xml file, the config file)
Ah yes I could do that, thanks for the clarification

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.