Home > other >  Passing one or multiple string parameters in controller method
Passing one or multiple string parameters in controller method

Time:03-06

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.

CodePudding user response:

It is throwing this error as you are returning a string when it expects an IActionResult. You can easily solve this by returning Ok($"Hello {id}");

CodePudding user response:

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}"));
}

CodePudding user response:

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}");
}
  • Related