2

I have a WebAPI controller and in circumstances I like to tell to the caller, that the content is malformed in form of a Bad Request response.

My operation method looks like this:

[HttpPost()]
public string Post([FromBody] ComplexType content) 
{
    // logic ...
}

I know that I can call this.BadRequest, but since my operation method has return type string, this helps me quite little.

How can I produce a Bad Request with the method shown above, without changing return type?

3
  • In that case your method has to throw an exception with the desired information. Additionally you have to add your own middleware that catches this exception and then returns the bad request response. But personally I like to use the ActionResult<> within the controller and handle these things in the concrete controller method. Commented Feb 15, 2022 at 14:06
  • Possible duplicate: Model State Validation in Web API Commented Feb 15, 2022 at 14:07
  • Maybe this could be of help: stackoverflow.com/questions/53558342/… Commented Feb 15, 2022 at 14:14

2 Answers 2

2

Just change it to this

[HttpPost()]
public  ActionResult<string> Post([FromBody] ComplexType content) 
{
    // logic ...

    return "string";
    //or
    return Ok();
    //or       
    return BadRequest("string");
}

it will still returns string, but 400 error too

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

Comments

2

You could decorate the Controller with [ApiController] attribute which will automatically add 400 BadRequest when ModelState is not valid.

The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

I've tested this for an Action which returns a string and the 400 error is sent successfully.


However, a better method (IMO) is to return an IActionResult (although you can still use [ApiController]). You then have more control over the response, and you could do something similar to the following:

[HttpPost()]
public IActionResult Post([FromBody] ComplexType content) 
{
    if (!ModelState.IsValid)
        return BadRequest();  // any custom message etc
    ...

    return Ok(yourString);
}

1 Comment

Thanks for that idea, unfortunatelly I loose the return type here, what exactly I didn't wanted to. But the solution from Serge combines your approach with the implementation of ActionResult<T>

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.