HTML Forms概述
<form action="api/values" method="post">
默认的method是GET,如果使用GET,表单数据被编码到URI中作为查询字符串;如果使用POST,表单数据放在Request body中,enctype
属性指定编码类型:
编码方式(enctype) | 描述 |
application/x-www-form-urlencoded | 表单数据被编码成name/value形式,默认的编码方式 |
multipart/form-data | 表单数据被编码成多部分的MIME消息,上传文件时使用 |
application/x-www-form-urlencoded
POST http://localhost:38899/api/updates/complex HTTP/1.1
Accept: text/html, application/xhtml+xml, /
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Content-Length: 47
status=Shopping+at+the+mall.&date=6%2F15%2F2012
注意:
默认情况下WebAPI获得复杂类型的参数使用Request body中,简单参数从URI中,可以使用[FromBody]
强制从Request body中获取。由于WebAPI最多读取Request body一次,所以action仅有一个参数是来自Request body,如果需要获取多个值从Request body可以使用复杂类型。
对于简单参数,在Request body中消息的格式:
=value
multipart/form-data
POST http://localhost:50460/api/values/1 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 29278
-----------------------------41184676334
Content-Disposition: form-data; name="caption"
Summer vacation
-----------------------------41184676334
Content-Disposition: form-data; name="image1"; >filename="GrandCanyon.jpg"
Content-Type: image/jpeg
(Binary data not shown)
-----------------------------41184676334--
Content-Disposition:包含上传控件的名字、上传的文件的名字
-
Content-Type:描述了这部分数据的类型。默认是text/plain可以省略
上传的一个demo
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
} string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root); try
{
await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData file in provider.FileData)
{
//文件名
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
//服务端存储文件路径
Trace.WriteLine("Server file path:"+file.LocalFileName);
}
//对应的name/value
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,e);
throw;
}
}
}