3 回答
TA贡献1794条经验 获得超8个赞
1)如果您必须发送Content-Type: multipart/form-data
或只是form-data
这是tab
邮递员的第一个
如果您只需要收集您发布的一个键/值对 form-data
[HttpPost]
[Route("api/test")]
public HttpResponseMessage TestMethod(HttpRequestMessage request)
{
var testValue = HttpContext.Current.Request.Form["test"];
return Request.CreateResponse(HttpStatusCode.OK, testValue);
}
如果您必须收集多个已发布的键/值对 form-data
[HttpPost]
[Route("api/test")]
public HttpResponseMessage TestMethod(HttpRequestMessage request)
{
NameValueCollection collection = HttpContext.Current.Request.Form;
var items = collection.AllKeys.SelectMany(collection.GetValues, (k, v) => new { key = k, value = v });
//We just collect your multiple form data key/value pair in this dictinary
//The following code will be replaced by yours
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
foreach (var item in items)
{
keyValuePairs.Add(item.key, item.value);
}
return Request.CreateResponse(HttpStatusCode.OK, keyValuePairs);
}
2)如果你必须发送 Content-Type: application/x-www-form-urlencoded
这是tab邮递员的第二个
那么你的 API 将是
[HttpPost]
[Route("api/test")]
public async Task TestMethod(HttpRequestMessage request)
{
var test = await request.Content.ReadAsFormDataAsync();
}
然后当您使用断点调试代码时,您将获得以下输出
3)如果你必须发送 Content-Type: application/json
这是tab
邮递员的第三个
有关此类选项,请参见下面的屏幕截图
你的api是
[HttpPost]
[Route("api/test")]
public async Task TestMethod(HttpRequestMessage request)
{
var jObject = await request.Content.ReadAsAsync<JObject>();
Item item = JsonConvert.DeserializeObject<Item>(jObject.ToString());
}
以及您收集这些发布数据的模型
public class Item
{
public string test { get; set; }
}
你的输出将是
此选项的优点是您可以将其complex type
作为发布的数据发送等
你的api是
[HttpPost]
[Route("test")]
public async Task TestMethod(HttpRequestMessage request)
{
var jObject = await request.Content.ReadAsAsync<JObject>();
Sample sample = JsonConvert.DeserializeObject<Sample>(jObject.ToString());
}
你收集这些数据的模型是
public class Item
{
public string test { get; set; }
}
public class Sample
{
public Item item { get; set; }
}
你会看到输出是
TA贡献1851条经验 获得超4个赞
从 Postman 发送并form-data选择选项时,以下代码将正确读取键/值
[HttpPost]
[Route("api/test")]
public async Task<HttpResponseMessage> TestMethod(HttpRequestMessage request)
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
var testValue = provider.FormData.GetValues("test")[0];
return Request.CreateResponse(HttpStatusCode.OK);
}
可以在此处找到更详尽的示例(部分:阅读表单控件数据)。
编辑:发送到上述 API 处理程序的 HTTP 调用如下:
POST /api/stats/testmethod HTTP/1.1
Host: localhost:4100
Cache-Control: no-cache
Postman-Token: 999fd13d-f804-4a63-b4df-989b660bcbc5
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="test"
esad
------WebKitFormBoundary7MA4YWxkTrZu0gW--
- 3 回答
- 0 关注
- 253 浏览
添加回答
举报