Search code examples
c#asp.net.netasp.net-mvcasp.net-mvc-routing

Asp.net MVC 5 make controller action to accept rest type parameters


I have a ASP.NET MVC5 application and I have written a new controller action in one of the controller.

I have a scenario where I to want call this new controller action from a different application(React).

Below is my new controller action.

public async Task<ActionResult> NewAction(int Id)
{
    var project = await _repository.GetProjectFromIdAsync(Id);
    if (project == null) return HttpNotFound();
    return RedirectToAction("ExistingAction", new { id = project.Id });
}

I can invoke the action successfully with this url - https://myapplicationlink/ControllerName/NewAction?Id=30

But I want to invoke the action with rest type url like https://myapplicationlink/ControllerName/NewAction/30

But when I do this I'm getting an error

The parameters dictionary contains a null entry for parameter 'Id'of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] NewAction(Int32)'

How do I make the action to accept rest type URL?


Solution

  • The parameter names in the route template placeholders are case sensitive.

    You have Id (upper-case I) while the template as id (lower case).

    This does not match the {controller}/{action}/{id} route template

    Rename the parameter to match route template Task<ActionResult> NewAction(int id) { ....

    public async Task<ActionResult> NewAction(int id) {
        var project = await _repository.GetProjectFromIdAsync(id);
        if (project == null) return HttpNotFound();
        return RedirectToAction("ExistingAction", new { id = project.Id });
    }