'Passing one or multiple string parameters in controller method

I have this controller method

//[HttpGet("{id}")] 
public IActionResult Nav(string id)
{
    return HtmlEncoder.Default.Encode($"Hello {id}");
    //return Content("Here's the ContentResult message.");
}

that i want to pass a string parameter and display it when i visit the controller method https://localhost:7123/Home/Nav/Logan. I get this error.

Cannot implicitly convert type 'string' to 'Microsoft.AspNetCore.Mvc.IActionResult'

I am using asp net core 6.



Solution 1:[1]

Let me explain.

  • When you perform following action.
return HtmlEncoder.Default.Encode($"Hello {id}");

This will return string and your method expect IActionResult so it get failed.

Solution 1

public string Nav(string id)
{
    return HtmlEncoder.Default.Encode($"Hello {id}");   
}

Now if you two paramter then you have to configure route that way. Default route only expect one Id.

[HttpGet("Nav/{id}/{two}")]
public string Nav(string id,string two)
{
    return HtmlEncoder.Default.Encode($"Hello {id},{two}");   
}

Solution 2

You can use Content or Ok Result and provide your output.

public IActionResult Nav(string id)
{
    return Ok(HtmlEncoder.Default.Encode($"Hello {id}"));
}

Solution 2:[2]

I fixed it this way. This is the url https://localhost:7123/Home/Nav/6?num=5&third=3

and this is the method

public IActionResult Nav(string id, int num, string third)
{
    return Ok($"Hello {id} {num} {third}");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2