我创建了一个期望表单数据的webApi。我将图像和数据都传递到WebAPI。当我使用PostMan传递参数时,我可以在模型中接收数据,并且在HttpContext.Current.Request.Files中可以访问文件。
现在,我想通过MVC控制器将相同的数据和图像传递给webapi。数据能够进入我的api方法,但要证明文件是一项艰巨的任务。 这是我的APi方法
[Route("Profile/EditUserProfileAsync")]
[HttpPost]
public async Task<HttpResponseMessage> EditUserProfile(UserProfile userProfile)
{
try
{
var Identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
int UserId = Convert.ToInt32(Identity.Claims.Where(c => c.Type == ClaimTypes.Sid).Select(c => c.Value).SingleOrDefault());
if (UserId == 0)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User Not Found!");
}
userProfile.UserId = UserId;
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var Result = await _userprofile.EditUserProfile(userProfile);
return Request.CreateResponse(HttpStatusCode.Created, Result);
}
catch (Exception ex)
{
await _log.logError(new ErrorLog() { CreatedDate = DateTime.Now, CustomMessage = "Error in EditUserProfile API", ErrorMessage = ex.Message, ModuleName = "UserProfile", StackTrace = ex.StackTrace });
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
这是api用来保存数据的方法
public async Task<MethodResult> EditUserProfile(UserProfile userProfile)
{
MethodResult methodResult = new MethodResult();
bool profileComplete = true;
try
{
if (userProfile.ImagePath == null && HttpContext.Current.Request.Files.Count == 0)
{
return new MethodResult() { Success = false, Message = "Profile Image is required !!" };
}
// some code here
}
catch(Exception ex)
{
// log error
}
}
在webapi的EditUserProfile方法中,此处文件计数始终为零
这是MVC控制器代码
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> SaveUserProfileDetails(UserProfile userProfile)
{
string Result = "true";
try
{
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Remove("Authorization");
client.DefaultRequestHeaders.Add("Authorization", identity.FindFirst("AcessToken").Value);
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(userProfile.FirstName), "FirstName");
form.Add(new StringContent(userProfile.UserId.ToString()), "UserId");
form.Add(new StringContent(userProfile.LastName), "LastName");
form.Add(new StringContent(userProfile.Designation), "Designation");
form.Add(new StringContent(userProfile.Gender.ToString()), "Gender");
form.Add(new StringContent(userProfile.City), "City");
form.Add(new StringContent(userProfile.Country), "Country");
form.Add(new StringContent(userProfile.DateOfBirth), "DateOfBirth");
form.Add(new StringContent(userProfile.Specialties), "Specialties");
if (Request.Files.Count > 0)
{
MemoryStream ms = new MemoryStream();
Request.InputStream.CopyTo(ms);
byte[] data = ms.ToArray();
ByteArrayContent fileContent = new ByteArrayContent(data);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { Name = "file"};
form.Add(fileContent);
}
else
{
form.Add(new StringContent(userProfile.ImagePath), "ImagePath");
}
var resp = await client.PostAsync(Constant.ApiBaseUri + "Profile/EditUserProfileAsync", form);
if (resp.IsSuccessStatusCode)
{
var result = await resp.Content.ReadAsStringAsync();
MethodResultVM<string> methodResult = JsonConvert.DeserializeObject<MethodResultVM<string>>(result);
Result = methodResult.Message;
}
else
{
Result = "false";
}
}
catch (Exception ex)
{
Result = "false";
}
return Json(Result, JsonRequestBehavior.AllowGet);
}
与此我释放标题中的输入流。但是我不希望那样,因为android和ios应用程序已经在使用相同的api,而且我也不想修改api。
请指导我如何从mvc控制器中的httpclient对象接收Web api控制器中的httpcontext中的IMAGE。