Shravan Kumar Kasagoni

Skip Navigation
How to use different name for action method in requested URL in MVC

How to use different name for action method in requested URL in MVC

 /  1 response

This articles talks about one simple technique that is when we make request for any resource/data in in server to ASP.NET MVC Web Application, the request is first processed by a method that is action method. Any public & non static method in a controller class is an action method.

Every action method inside the controller can be invoked via URL. If we look at general URL structure: http://{hostname}/{controller-name}/{action-name}/{parameters}

It’s not mandatory that URL will be in same structure, we have flexibility to have any kind of structure (e.g: http://hostname/xyz), but finally request should be mapped to action method in a controller for processing request. For example I have a HomeController, inside that an action method named GetProducts(), now if want to get the list of products I should invoke GetProducts() action method, generally the requested URL looks like this: http://{hostname}/Home/GetProducts

But I don’t want to expose the my actual action method name to the client, so I want to use different name in request URL, it I will mapped to an actual action method name at runtime. I want to use the requested resource name as Products in URL & actual action method as GetProducts(). Now the requested URL is http://{hostname}/Home/Products, but this should invoke GetProducts() in home controller.

ASP.NET MVC provides a very simple way of doing this using an attribute named [ActionName()] on action method.

Now the action method name is no longer a valid name for URL for accessing the resources provided by action method. One more thing to remember is If we are using View() method, this method uses action method name as view name by default. As we are not specifying any view name & we are using [ActionName()] attribute, then the action method name is not valid default view name, The default view name is also the name specified in [ActionName()] attribute.

If try to use actual action method name in requested URL , MVC will return HTTP 404 status code (resource not found).

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.

Discussion

Close Bitnami banner
Bitnami