IHttpActionResult return Json object
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});
Ajay
Updated on January 28, 2020Comments
-
Ajay over 4 years
I have created one method in
mvc api
which returns string. But instead of returningstring
, I want to returnJson 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 returnJson object
. How can I return Json object? -
Ajay over 9 yearsHi 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 over 9 yearsTry to create POCO class then
-
Ajay over 9 yearsHow can I create it? can you please post the code for it?
-
Ajay over 9 yearsI tried
JsonConvert.SerializeObject(passResponse)
but it gives"{\"email\":\"[email protected]\"}"
I don't want these `` -
incutonez almost 9 yearsIt wasn't clear to me why I'd want to return a plain string, so I did something like
return Json(new {success = true});