0

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.

3 Answers 3

1

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

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

4 Comments

How come this is not possible public IActionResult Nav(string id, int num) { return Ok($"Hello {id} {num}"); }
Sorry this works https://localhost:7123/Home/Nav/6?num=5
What you are referring to is routing. Your original question has [HttpGet("{id}")] which means that the action method is expecting something like /Home/Nav/{id}. If you do not declare a route, your url would be https://localhost:7123/Home/Nav?id=6&num=5
@Gandalf if you agree with my comment could you please accept my answer.
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}"));
}

1 Comment

In the first solution, can i have a parameter of type string and int or list? I am trying this public string Nav(string id, string two) { return two; //return Content("Here's the ContentResult message."); } but fails
0

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

Comments

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.