我正在使用视图上载照片,然后在控制器中将其接收为HttpPostedFileBase
然后我发送一个http请求,一切都很好,但是当我在json对象中接收到http请求时,照片会显示为空`
请求如下:
public ActionResult RegisterUsersCheck(User_all_data user_data)
{
var webAddr = "http://localhost:59305/api/User/RegisterUsersCheck";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ user : { 'FirstName':'" + user_data.user.FirstName +
"','LastName': '" + user_data.user.LastName + "','Email': '" + user_data.user.Email +
"','Password': '" + user_data.user.Password + "','Country': '" + user_data.user.Country +
"','PhoneNumber': '" + user_data.ProfilePicture +
"'},'ProfilePicture': '" + user_data.PhoneNumber + "'}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return RedirectToAction("Index");
}
以下是我如何收到请求的
public bool RegisterUsersCheck ([FromBody] User_all_data user_ext)
{
List<User> all_users = repo.getUsers();
var match = all_users.Find(i => i.Email == user_ext.user.Email);
if (match == null)
{
RegisterUsers(user_ext);
return true;
}
else
{
return false;
}
}
这里是
User_all_data
类public class User_all_data
{
public User user { get; set; }
public HttpPostedFileBase ProfilePicture { get; set; }
}
如前所述,发送是可以的,但是当我收到请求时
ProfilePicture
是空的 最佳答案
首先,在这段代码中
string json = "{ user : { 'FirstName':'" + user_data.user.FirstName +
"','LastName': '" + user_data.user.LastName + "','Email': '" + user_data.user.Email +
"','Password': '" + user_data.user.Password + "','Country': '" + user_data.user.Country +
"','PhoneNumber': '" + user_data.ProfilePicture +
"'},'ProfilePicture': '" + user_data.PhoneNumber + "'}";
似乎键
PhoneNumber
和ProfilePicture
被交换了。您将PhoneNumber
设置为ProfilePicture
,ProfilePicture
设置为PhoneNumber
。应该是相反的。另外,我不确定
user_data.ProfilePicture
是什么数据类型,但如果它是一个图像,就不能将其填充到json中。json不支持像图像那样的二进制数据。一个选项是在将图像数据放入json之前对其进行base64编码。下面是一个这样做的示例:byte[] imageBytes = ...
var imageBytesStr = Convert.ToBase64String(imageBytes);
然后在构造json时,将
ProfilePicture
键设置为base64编码的字符串imageBytesStr
。然后,您的客户机必须对ProfilePicture
字符串进行base64解码才能获取图像字节。然后客户端必须从这些字节构造一个映像。