IHttpActionResult 返回 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27165378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IHttpActionResult return Json object
提问by Ajay
I have created one method in mvc apiwhich returns string. But instead of returning string, I want to return Json Object. Here is my code.
我创建了一种mvc api返回字符串的方法。但string我不想返回,而是想返回Json Object。这是我的代码。
[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?
这里它返回Ok<string>(newPassword);现在我想返回Json object。如何返回Json 对象?
回答by Sergejs
Try that:
试试看:
[AllowAnonymous]
[HttpPost]
[Route("resetpassword")]
public IHttpActionResult ResetPassword(string email)
{
//...
return Json(newPassword);
}
回答by user3682091
You are actually already using the key thing...
你实际上已经在使用关键的东西......
[HttpGet]
public IHttpActionResult Test()
{
return Ok(new {Password = "1234"});
}
回答by Taiseer Joudeh
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:
您需要将其作为 CLR 对象返回,以便 Web API 将其序列化为 JSON,您可以创建自己的 POCO 类或这样做:
var passResponse = new
{
newPassword= yourNewPassword
};
But from security standpoint what you are doing is not correct, you should NEVERsend 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.
但是从安全角度来看,您所做的事情是不正确的,您永远不应该通过电子邮件发送普通密码,您应该通过向他们提供带有一些令牌的重置电子邮件链接到您的门户来重置用户密码,并且他们应该输入新密码。你在这里所做的并不安全。
回答by Kyle Huang
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});
return OK(new PasswordResponse(){Password = newPassword});

