C# 多部分/表单数据请求为空
我试图在C# 多部分/表单数据请求为空,c#,xamarin,asp.net-web-api2,C#,Xamarin,Asp.net Web Api2,我试图在MultipartFormDataContent对象中上载一个图像和一些json数据。但是由于某些原因,我的webapi没有正确地接收请求。最初,api以415响应彻底拒绝了请求。为了解决这个问题,我在WebApiConfig.cs public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure W
MultipartFormDataContent
对象中上载一个图像和一些json数据。但是由于某些原因,我的webapi没有正确地接收请求。最初,api以415响应彻底拒绝了请求。为了解决这个问题,我在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;
}
[HttpPost]
公共SimpleResponse上载映像(映像操作)
{
SimpleResponse ReturnValue=新的SimpleResponse();
尝试
{
if(HttpContext.Current.Request.Files.AllKeys.Any())
{
var httpPostedFile=HttpContext.Current.Request.Files[“uploadeImage”];
var httpPostedFileData=HttpContext.Current.Request.Form[“imageDetails”];
if(httpPostedFile!=null)
{
MiscFunctions misctools=新的MiscFunctions();
字符串文件名=User.Identity.Name+“”+misctools.ConvertDateTimeToUnix(DateTime.Now)+“.jpg”;
字符串路径=User.Identity.Name+“/”+DateTime.Now.ToString(“yyyy-mm-dd”);
字符串完整路径=路径+文件名;
UploadedFilesUploadedImageDetails=JsonConvert.DeserializeObject(httpPostedFileData);
上传的_文件imageDetails=新上传的_文件();
imageDetails.FileName=文件名;
imageDetails.ContentType=“image/jpeg”;
imageDetails.DateCreated=DateTime.Now;
imageDetails.UserID=User.Identity.GetUserId();
imageDetails.FullPath=完整路径;
Stream imageStream=httpPostedFile.InputStream;
int imageLength=httpPostedFile.ContentLength;
字节[]图像=新字节[imageLength];
读取(图像,0,图像长度);
Image_Data imageObject=新的Image_Data();
imageObject.Image_Data1=图像;
使用(var context=new trackerEntities())
{
context.Image\u Data.Add(imageObject);
SaveChanges();
imageDetails.MediaID=imageObject.ImageID;
context.upload\u Files.Add(imageDetails);
SaveChanges();
}
ReturnValue.Success=true;
ReturnValue.Message=“成功”;
ReturnValue.ID=imageDetails.ID;
}
}
其他的
{
ReturnValue.Success=false;
ReturnValue.Message=“空请求”;
ReturnValue.ID=0;
}
}
捕获(例外情况除外)
{
ReturnValue.Success=false;
ReturnValue.Message=ex.Message;
ReturnValue.ID=0;
}
返回值;
}
Xamarin应用程序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;
}
公共异步任务上载映像(ImageUpload操作)
{
SimpleResponse ReturnValue=新的SimpleResponse();
NSUserDefaults GlobalVar=NSUserDefaults.StandardUserDefaults;
字符串标记=GlobalVar.StringForKey(“标记”);
TaskCompletionSource tcs=新的TaskCompletionSource();
尝试
{
使用(HttpClient HttpClient=new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“承载者”,令牌);
httpClient.DefaultRequestHeaders.Add(“接受”、“应用程序/xml”);
使用(var httpContent=new MultipartFormDataContent())
{
ByteArrayContent baContent=新的ByteArrayContent(action.Image.Data);
baContent.Headers.ContentType=新的MediaTypeHeaderValue(“图像/Jpeg”);
字符串jsonString=JsonConvert.SerializeObject(action.UploadFiles);
StringContent StringContent=新的StringContent(jsonString);
stringContent.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/json”);
使用(HttpResponseMessage httpResponse=await httpClient.PostAsync)(新Uri(“http://10.0.0.89/api/Location/UploadImage(http://httpContent)
{
字符串returnData=httpResponse.Content.ReadAsStringAsync().Result;
SimpleResponse jsondoc=JsonConvert.DeserializeObject(returnData);
ReturnValue.ID=jsondoc.ID;
ReturnValue.Message=jsondoc.Message;
ReturnValue.Success=jsondoc.Success;
}
}
}
}
捕获(WebException ex)
{
ReturnValue.Success=false;
if(ex.Status==WebExceptionStatus.Timeout)
{
ReturnValue.Message=“请求超时。”;
}
其他的
{
ReturnValue.Message=“Error”;
}
设置结果(返回值);
}
//...code removed for brevity
httpContent.Add(baContent, "uploadedImage");
httpContent.Add(stringContent, "imageDetails");
//...send content
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);
}