简体   繁体   中英

MVC null route ID takes me to spa(angular) rather than returning a bad request

I've been searching for this question for a while but have yet to find an answer. In a nutshell, I have a .net core web application using the angular spa template. I have multiple controllers that act as APIs and in general everything works fine. However in the following situation, I'm curious if there is another way to accomplish a null id being sent WITHOUT overloading the action.

Here is what I have and works as expected:

[HttpGet("[action]")]
public IActionResult SayHello()
{
    return BadRequest(new
    {
        error = "Name registered as null.",
        message = "No value(null) was provided to the api resource 'SayHello' which resulted in no action taken."
    });
}

[HttpGet("[action]/{name}")]
public IActionResult SayHello(string name)
{
    return Ok($"Hello {name}");
}

What I want to know is this, can I accomplish this WITHOUT overloading? For example, simply do this:

[HttpGet("[action]/{name}")]
public IActionResult SayHello(string name)
{
    if (name == null)
    {
        return BadRequest(new
        {
            error = "Name registered as null.",
            message = "No value(null) was provided to the api resource 'SayHello' which resulted in no action taken."
        });
    }
    return Ok($"Hello {name}");
}

Currently when I attempt this, the null id route will be treated as if it doesn't exist and the route will be passed to angular to deal with. Is overloading the preferred and only way to accomplish this? Or is there another way?

Found the answer and it's rather simple. Just need to add another attribute to the action method.

[HttpGet("[action]")]
[HttpGet("[action]/{name}")]
public IActionResult SayHello(string name)
{
    if (name == null)
    {
        return BadRequest(new
        {
            error = "Name registered as null.",
            message = "No value(null) was provided to the api resource 'SayHello' which resulted in no action taken."
        });
    }
    return Ok($"Hello {name}");
}

Depending on what you do in the front end it is important to remember that the string can be empty rather than null. Additionally, you will then have to remove the route without the parameter. Consider the code below:

[HttpGet("[action]/{name}")]
public IActionResult SayHello(string name)
{
    if (string.IsNullOrEmpty(name))//this
    {
        return BadRequest(new
        {
            error = "Name registered as null.",
            message = "No value(null) was provided to the api resource 'SayHello' which resulted in no action taken."
        });
    }
    return Ok($"Hello {name}");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM