我正在使用Web API - Web API 2.我的基本需求是创建一个API来更新用户的配置文件.在这里,ios和android会以multipart/form-data的形式向我发送请求.他们会向我发送一些图像参数.但每当我尝试创建API时,我的模型每次都变为null.
我在WebApiConfig中添加了这一行:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
Run Code Online (Sandbox Code Playgroud)
这是我的班级:
public class UpdateProfileModel
{
public HttpPostedFileBase ProfileImage { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
[Route("api/Account/UpdateProfile")]
[HttpPost]
public HttpResponseMessage UpdateProfile(UpdateProfileModel model)
{
}
Run Code Online (Sandbox Code Playgroud)
我甚至没有在我的模型中获取参数值.难道我做错了什么 ?
没有与此相关的答案对我有帮助.它大约第3天,我已经尝试了几乎所有的方法.但我无法实现它.
虽然我可以使用它,但如下所示,但这似乎不是一个好方法.所以我避免它..
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Form["ParameterName"] != null)
{
var parameterName = httpRequest.Form["ParameterName"];
}
Run Code Online (Sandbox Code Playgroud)
对于文件,我可以这样做:
if (httpRequest.Files.Count > 0)
{
//i can access my files here and save them
}
Run Code Online (Sandbox Code Playgroud)
如果您有任何好的方法,请帮助或者请解释我为什么我无法在模型中获得此值.
非常感谢提前
我遇到了关于从HttpInputStream到FileStream的转换类型的问题.
我怎么做的?
我有一个HttpPostedFileBase对象,我想拥有FileStream.
我写:
public void Test(HttpPostedFileBase postedFile) {
FileStream fileStream = (FileStream)(postedFile.InputStream); // throw exception
FileStream anotherFileStream = postedFile.InputStream as FileStream; // null
}
Run Code Online (Sandbox Code Playgroud)
我也试过了
public void Test(HttpPostedFileBase postedFile) {
Stream stream = postedFile.InputStream as Stream;
FileStream myFile = (FileStream)stream;
}
Run Code Online (Sandbox Code Playgroud)
但没有成功.
为什么要postedFile.InputStream来HttpInputStream型?
我怎么能解决这个问题呢?
谢谢
public ActionResult Import(HttpPostedFileBase currencyConversionsFile)
{
string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv";
string folderPath = Server.MapPath("~/Files/");
string filePath = Server.MapPath("~/Files/" + filename);
currencyConversionsFile.SaveAs(filePath);
string[] csvData = System.IO.File.ReadAllLines(filePath);
//the later code isn't show here
}
Run Code Online (Sandbox Code Playgroud)
我知道将httppostedfilebase转换为String数组的常用方法,它首先将文件存储在服务器中,然后从服务器读取数据.无论如何直接从httppostedfilebase获取字符串数组而不将文件存储到服务器中?