我正在尝试在MultipartFormDataContent
对象中上传图像和一些json数据。但是我的webapi由于某种原因没有正确收到请求。最初,api完全拒绝了415请求的请求。为了解决这个问题,我将多部分/表单数据的xml格式化程序添加到WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
这似乎在很大程度上起作用,我使用ARC测试它并且它接收了多部分的所有部分,唯一的问题是字符串内容没有出现在表单中,它在文件中但我把它归结为没有被格式化为StringContent
对象的请求。
我当前遇到的问题是我的Xamarin应用程序在发送多部分请求时似乎没有发布任何内容。当请求到达API控制器时,内容标题就在那里,但文件和表单字段都是空的。
在做了一些研究之后,似乎我必须编写一个自定义的MediaTypeFormatter
,但我发现的那些似乎都不是我想要的。
以下是我的其余代码:
Api控制器:
[HttpPost]
public SimpleResponse UploadImage(Image action)
{
SimpleResponse ReturnValue = new SimpleResponse();
try
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
var httpPostedFile = HttpContext.Current.Request.Files["uploadedImage"];
var httpPostedFileData = HttpContext.Current.Request.Form["imageDetails"];
if (httpPostedFile != null)
{
MiscFunctions misctools = new MiscFunctions();
string fileName = User.Identity.Name + "_" + misctools.ConvertDateTimeToUnix(DateTime.Now) + ".jpg";
string path = User.Identity.Name + "/" + DateTime.Now.ToString("yyyy-mm-dd");
string fullPath = path + fileName;
UploadedFiles uploadedImageDetails = JsonConvert.DeserializeObject<UploadedFiles>(httpPostedFileData);
Uploaded_Files imageDetails = new Uploaded_Files();
imageDetails.FileName = fileName;
imageDetails.ContentType = "image/jpeg";
imageDetails.DateCreated = DateTime.Now;
imageDetails.UserID = User.Identity.GetUserId();
imageDetails.FullPath = fullPath;
Stream imageStream = httpPostedFile.InputStream;
int imageLength = httpPostedFile.ContentLength;
byte[] image = new byte[imageLength];
imageStream.Read(image, 0, imageLength);
Image_Data imageObject = new Image_Data();
imageObject.Image_Data1 = image;
using (var context = new trackerEntities())
{
context.Image_Data.Add(imageObject);
context.SaveChanges();
imageDetails.MediaID = imageObject.ImageID;
context.Uploaded_Files.Add(imageDetails);
context.SaveChanges();
}
ReturnValue.Success = true;
ReturnValue.Message = "success";
ReturnValue.ID = imageDetails.ID;
}
}
else
{
ReturnValue.Success = false;
ReturnValue.Message = "Empty Request";
ReturnValue.ID = 0;
}
}
catch(Exception ex)
{
ReturnValue.Success = false;
ReturnValue.Message = ex.Message;
ReturnValue.ID = 0;
}
return ReturnValue;
}
Xamarin App Web请求:
public async Task<SimpleResponse> UploadImage(ImageUpload action)
{
SimpleResponse ReturnValue = new SimpleResponse();
NSUserDefaults GlobalVar = NSUserDefaults.StandardUserDefaults;
string token = GlobalVar.StringForKey("token");
TaskCompletionSource<SimpleResponse> tcs = new TaskCompletionSource<SimpleResponse>();
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/xml");
using (var httpContent = new MultipartFormDataContent())
{
ByteArrayContent baContent = new ByteArrayContent(action.Image.Data);
baContent.Headers.ContentType = new MediaTypeHeaderValue("Image/Jpeg");
string jsonString = JsonConvert.SerializeObject(action.UploadFiles);
StringContent stringContent = new StringContent(jsonString);
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpResponseMessage httpResponse = await httpClient.PostAsync(new Uri("http://10.0.0.89/api/Location/UploadImage"), httpContent))
{
string returnData = httpResponse.Content.ReadAsStringAsync().Result;
SimpleResponse jsondoc = JsonConvert.DeserializeObject<SimpleResponse>(returnData);
ReturnValue.ID = jsondoc.ID;
ReturnValue.Message = jsondoc.Message;
ReturnValue.Success = jsondoc.Success;
}
}
}
}
catch(WebException ex)
{
ReturnValue.Success = false;
if (ex.Status == WebExceptionStatus.Timeout)
{
ReturnValue.Message = "Request timed out.";
}
else
{
ReturnValue.Message = "Error";
}
tcs.SetResult(ReturnValue);
}
catch (Exception e)
{
ReturnValue.Success = false;
ReturnValue.Message = "Something went wrong";
tcs.SetResult(ReturnValue);
}
return ReturnValue;
}
答案 0 :(得分:0)
答案 1 :(得分:-1)
try
{
var jsonData = "{your json"}";
var content = new MultipartFormDataContent();
content.Add(new StringContent(jsonData.ToString()), "jsonData");
try
{
//Checking picture exists for upload or not using a bool variable
if (isPicture)
{
content.Add(new StreamContent(_mediaFile.GetStream()), "\"file\"", $"\"{_mediaFile.Path}\"");
}
else
{
//If no picture for upload
content.Add(new StreamContent(null), "file");
}
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + exc);
}
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(new Uri("Your rest uri"), content);
if (response.IsSuccessStatusCode)
{
//Do your stuff
}
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + e);
}
其中_mediaFile是从图库或相机中选择的文件。 https://forums.xamarin.com/discussion/105805/photo-json-in-xamarin-post-webservice#latest