4

I have built an ASP.NET Core MVC application and I have used the default MVC URL routing:

app.UseMvc(routes =>
{
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

I want to create the GET method for creating and editing the user.

For creating new user I need to go to url /Admin/User and for editing the existing user url /Admin/User/{id:int}

I have tried to create the method like this:

[HttpGet]
public async Task<IActionResult> User(int? id)
{
}

How can I restrict type of the id parameter?

I need only allow access to /Admin/User or /Admin/User/{id:int} - but if I try i.e. - /Admin/User/ABCD - (use an string as ID) - it is allowed as well.

If the parameter ID will be another type instead of number then I want to return 404.

3 Answers 3

2

The simplest option is to create a route with this constraint. Note that if you make the parameter required in the route like this, there is no reason to make id nullable.

[HttpGet("Admin/User")]
public async Task<IActionResult> Add()
{
}

[HttpGet("Admin/User/{id:int}")]
public async Task<IActionResult> Edit(int id) 
{
}

Or keep the action methods named User and use:

app.UseMvc(routes =>
{
    routes.MapRoute("AdminUser", "Admin/User/{id:int}");
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

Note that the convention-based approach doesn't differentiate between GET/POST.

Alternatively, if you want to make all of your ID parameters an int, you could configure the routing for the whole site like this:

routes.MapRoute(
    name: "defaultWithId",
    template: "{controller}/{action}/{id:int}");
routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}");

Reference: Routing in ASP.NET Core

Sign up to request clarification or add additional context in comments.

2 Comments

How can I create a view for creating new user? For this reason I want to create ID nullable.
It would be best to use an action method for create and another action method for edit - separation of concerns. And all of these routing configurations cover that.
0

You would have to write a custom model binder for this, or create an overload for every other type which returns the 404. I would simply rethink your design and have a different /Admin/CreateUser action for creating a new user instead and just not allow the User call without an ID.

4 Comments

I have used single view for these type of actions - for creating and editing - is it possible create two type of method like you mentioned - /Admin/CreateUser and /Admin/EditUser and use the same view?
yes it is possible with same method names but different arguments (different signature)
@Jenan You can use the same view simply by specifying the name of the view when calling View, eg. - return View("viewName", modelObject); in both Actions just use the same view name
Thank you - what do you mean with same method names?
0

It is possible to achieve using single method.

If you are using numeric ids then for existing user id will be greater than zero. For new user Id will be zero or less than zero.

If you are using string ids then for existing user, id will be non-empty string. E.g. ABCD. For new user Id will be empty.

Based on this logic you can you can send appropriate response or 404 response. If you are using string Ids, then change the data type of Get method. Instead of using nullable int use string.

Following code might help

[HttpGet("{id}")]
    public async Task<IActionResult> User(string id)
    {
        if (string.IsNullOrWhiteSpace(id))
        {
            //Replace NewUser view name by Appropriate View name in your project
            return View("NewUser");
        }
        else
        {
           var isValidUser= IsValidUser(id);
            if(isValidUser)
            {
                //Replace ExistingUser view name by Appropriate View name in your project
                return View("ExistingUser");
            }
            else
            {
                //User Appropriate overload of NotFound
                return NotFound();
            }
        }
    }
    private bool IsValidUser(string userId)
    {
        //Your logic to validate the existing user.            
    }

1 Comment

Can you please modify this User method for ID type integer? For this reason I used the nullable ID param.

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.