Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't FromQuery working in my ASP.Net Core 1.1 controller action

I am working on an ASP.Net Core 1.1 web API. I have a ServiceTypeCode controller as shown below;

[Produces("application/json")]
[Route("api/[controller]")]
public class ServiceTypeCodeController : Controller
{ 
    ...
    ...
    ...


    [HttpGet]
    public IActionResult Get([FromQuery] string a_query)
    {
        try
        {
            if (string.IsNullOrEmpty(a_query))
            {
                OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes();
                if (result.Success && result.Result.Count > 0)
                {
                    return Ok(JsonConvert.SerializeObject(result.Result));
                }
            } else
            {
                // Deserialize query into dictionary of strings and StringValues 
                var query = QueryHelpers.ParseQuery(a_query.ToLower());

                if (query.TryGetValue("mailclasscode", out var mailClassCode))
                {
                    if (!string.IsNullOrEmpty(mailClassCode))
                    {
                        OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes(mailClassCode);
                        if (result.Success && result.Result.Count > 0)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
                if (query.TryGetValue("stc", out var stc))
                {
                    if (!string.IsNullOrEmpty(stc))
                    {
                        OperationResult<ServiceTypeCode, string> result = m_bl.GetServiceTypeCode(stc);
                        if (result.Success)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            string msg = "An exception occurred while trying to get a list of ServiceTypeCodes from the database.";
            m_logger.LogError(1, ex, msg);
            ApiError error = BuildError("Server Error - Exception", "500", "Get", ex, msg);
            return Ok(JsonConvert.SerializeObject(error));
        }

    }

If I use the url ...

http://localhost:5000/api/servicetypecodes

in PostMan with the GET verb, I get the list of service type codes, as expected. However, If I try to add anything as a query string, such as ...

http://localhost:5000/api/servicetypecodes?mailclasscode=fc

and set a breakpoint in my code at the

if (string.IsNullOrEmpty(a_query))

location, the value of a_query is null instead of the expected "mailclasscode=fc"

What am I missing here?

Thanks in advance for any help.

like image 877
EiEiGuy Avatar asked Jul 07 '17 16:07

EiEiGuy


People also ask

What is difference between FromQuery and FromBody?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

What is the best way to define a return type of an web API core action method?

Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200). Alternatively, convenience methods in the ControllerBase class can be used to return ActionResult types from an action.

How do I return a response in .NET core API?

IActionResult Return Type in ASP.NET Core Web API: The IActionResult is an interface and it is used to return multiple types of data. For example, if you want to return NotFound, OK, Redirect, etc. data from your action method then you need to use IActionResult as the return type from your action method.

What is IActionResult in .NET core?

IActionResult specifies how the server should respond to the request, such as writing data to the response or returning an error status code. For example, Microsoft. AspNetCore. Mvc.


2 Answers

The .Net Core Controller Method's variable names must be the same as what you are sending.

http://localhost:5000/api/servicetypecodes?mailclasscode=fc

If using that url to pass data the controller method will have to look like this:

[HttpGet]
public IActionResult Get([FromQuery] string mailclasscode)
{...}

Or vice versa.

Good luck - happy coding.

like image 164
Terrance00 Avatar answered Dec 19 '22 02:12

Terrance00


You can have the query string name differ from the variable name in the method. You have to let .NetCore know how by defining it in code like so (using your variable names):

[HttpGet]
public IActionResult Get([FromQuery(Name = "mailclasscode")] string a_query)
{
   ...
}

or more generically:

[HttpGet]
public IActionResult Get([FromQuery(Name = "myQueryStringParamName")] string myCodeParamName)
{
   ...
}
like image 41
ono2012 Avatar answered Dec 19 '22 01:12

ono2012