Monday, May 1, 2017

Asp.net Core/MVC routing

Routing is necessary for controlling the accessible path in the URL.

1) In the Startup.Configure proc, you can add a route to "ContactUs" that looks like this:

            app.UseMvc(route =>
            {
                // adding a new route for http://localhost:57477/contactUs
                route.MapRoute(name: "contact_us",
                            template: "contactUs",
                            defaults: new { controller = "Home", action = "ContactUs" });

                // if the path in the url is blank, call HomeController.
                route.MapRoute(name: "default",
                                template: "{controller=Home}/{action=Index}/{id?}");

            });

And the HomeController looks like below. Simple and straight forward.

    public class HomeController : Controller
    {
        // returns the default page.
        public IActionResult Index()
        {
            return View();
        }

        //returns the contact us page.
        public IActionResult ContactUs()
        {
            return View();
        }
    }

2) You may also add a new route by adding HttpGet attribute to the method and add Route attribute to the class.

    [Route("[controller]")]
    public class ValuesController : Controller
    {
        // GET values
        // http://localhost:57477/values/
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET values/5
        // http://localhost:57477/values/7890
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value=" + id.ToString();
        }

        // GET values/getjson/5
        //http://localhost:57477/values/getjson/1234
        // returns the data in json format.
        [HttpGet("GetJson/{id?}")]
        public IActionResult GetJson(int id)
        {
            var v = new { v = "value=" + id.ToString() };
            return new ObjectResult(v);
        }
    }

No comments:

Post a Comment