Paradigm
Paradigm

Reputation: 189

How would one successfully return a BadRequest with an MVC Model?

My aim is to create a bad request response that passes an object with it. The reason for this is to create consistency with my return types. I have tried serializing as a JSON serialize but the response was not the same as sending the object.

So if there is any way at all that this can be sent, it would be great to know. Also, I know there is a method of doing this in .NET core but I would rather use just .Net as I have more options and I am working with other projects that rely on this.


    // POST: api/postLogin
    [AllowAnonymous]
    [System.Web.Http.HttpPost, System.Web.Http.Route("postlogin")]
    public async Task<IHttpActionResult> PostLogin(LoginDTO login)
    {    
       OutputDTO<LoginDTO> output = new OutputDTO<LoginDTO>();

       LoginDTO loginDTO = null;
       try
       { 
          if (!ModelState.IsValid)
          {
             output.Success = false;
             output.SetValidations(ModelState);
             output.ErrorMessage = "Invalid Model";                   
             return BadRequest(output);
          }
          login newLogin = new login();

          string encryptedPassword = Crypto.ApplyPasswordObfuscation(login.Password, true);
          login loginUser = await _context.login.SingleOrDefaultAsync(m =>
                          m.name == login.Username && m.password == encryptedPassword);

          if (loginUser == null)
          {
             output.Success = false;
             output.ErrorMessage = "Invalid login credentials";
             var json = new JavaScriptSerializer().Serialize(output);
             return BadRequest(json); // Not 401, since you don't want to return to the login page. Client will be already on login page
          }
          else
          {
             loginDTO = new LoginDTO(loginUser);
             output.Success = true;
             output.Results = new List<LoginDTO>
             {
                loginDTO
             };
             return Ok(output);
          }                
       }
       catch (Exception e)
       {
          output.Success = false;                
          output.ErrorMessage = "Login " + e;                
          return BadRequest(output);
       }            
    }

Upvotes: 0

Views: 2250

Answers (1)

Craig H
Craig H

Reputation: 2071

You should be able to return a "Content" and specify a status code and an object.
e.g.

return this.Content(HttpStatusCode.BadRequest, output);

Upvotes: 1

Related Questions