IHttpActionResult return Json object

34,055

Solution 1

Try that:

[AllowAnonymous]
[HttpPost]
[Route("resetpassword")]
public IHttpActionResult ResetPassword(string email)
{
    //...
    return Json(newPassword);
}

Solution 2

You are actually already using the key thing...

[HttpGet]
public IHttpActionResult Test()
{
     return Ok(new {Password = "1234"});
}

Solution 3

You need to return it as CLR object so Web API serialize it to JSON, you can create your own POCO class or do it like this:

 var passResponse =  new
              {
                  newPassword= yourNewPassword
              };

But from security standpoint what you are doing is not correct, you should NEVER send plain passwords by email, you should reset user password by providing them a reset email link to your portal with some token and they should enter the new password. What you are doing here is not secure.

Solution 4

Create a return object.

public class PasswordResponse{
    public string Password {get;set;}
    //...other stuff to pass...
}

Then return an instance of the type in your response.

return OK(new PasswordResponse(){Password = newPassword});

Share:
34,055
Ajay
Author by

Ajay

Updated on January 28, 2020

Comments

  • Ajay
    Ajay over 4 years

    I have created one method in mvc api which returns string. But instead of returning string, I want to return Json Object. Here is my code.

        [AllowAnonymous]
        [HttpPost]
        [Route("resetpassword")]
        public IHttpActionResult ResetPassword(string email)
        {
            CreateUserAppService();
            string newPassword =_userAppService.ResetPassword(email);
    
            string subject = "Reset password";
            string body = @"We have processed your request for password reset.<br/><br/>";
            string from = ConfigurationManager.AppSettings[Common.Constants.FromEmailDisplayNameKey];
            body = string.Format(body, newPassword, from);
    
            SendEmail(email, subject, body, string.Empty);
            return Ok<string>(newPassword);
        }
    

    Here it returns Ok<string>(newPassword); Now I want to return Json object. How can I return Json object?

  • Ajay
    Ajay over 9 years
    Hi Taiseer, Thank you for reply. I tried your code. It returns me "{ newPassword = FER3P74G }" But I want something like { "newPassword" :" FER3P74G" }. How can I do this?
  • Taiseer Joudeh
    Taiseer Joudeh over 9 years
    Try to create POCO class then
  • Ajay
    Ajay over 9 years
    How can I create it? can you please post the code for it?
  • Ajay
    Ajay over 9 years
    I tried JsonConvert.SerializeObject(passResponse) but it gives "{\"email\":\"[email protected]\"}" I don't want these ``
  • incutonez
    incutonez almost 9 years
    It wasn't clear to me why I'd want to return a plain string, so I did something like return Json(new {success = true});