【发布时间】:2016-08-25 07:47:31
【问题描述】:
我正在尝试使用 WebApi,但遇到了问题。我的“IsSuccessStatusCode”总是错误的,我有 404 作为回应。
我尝试了多种方法,但都无法正确完成。
常量:
const string baseUri = ""; // base url of API
const string setDealFlagUri = "Deals/SetDealFlag";
方法一,使用 PostAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("deadId", "3"),
new KeyValuePair<string, string>("flagValueToSet", "true")
});
var response = await client.PostAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
方法二,使用 PostAsJsonAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
DealFlag content = new DealFlag
{
deadId = 3,
flagValueToSet = true
};
var response = await client.PostAsJsonAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
WebApi 请求详情:
卷曲:
curl -X POST --header 'Accept: application/json' '{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true'
请求网址
{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true
响应正文
{
"Successful": true,
"ErrorMessages": [],
"ValidationResults": {
"IsValid": false,
"ValidationErrors": []
}
}
响应标头
{
"pragma": "no-cache",
"date": "Wed, 24 Aug 2016 18:38:01 GMT",
"content-encoding": "gzip",
"server": "Microsoft-IIS/8.0",
"x-aspnet-version": "4.0.30319",
"x-powered-by": "ASP.NET",
"vary": "Accept-Encoding",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"content-length": "198",
"expires": "-1"
}
请帮我正确使用这个webapi函数。 谢谢!
【问题讨论】:
-
什么问题?
IsSuccessStatusCode总是false?如果是这样,response中的内容是什么? -
是的,“IsSuccessStatusCode”始终为假。我有 404 响应。
-
@Saadi 404 - 表示未找到。所以先检查你的网址
-
网址对我来说似乎没问题。我还在我的问题中添加了我的 url 常量。你可以检查一下。好像还可以
-
@Saadi 我不完全确定,但我可以看到您通过 URL 发送数据,而不是作为表单(使用 cURL)。您是否尝试将您的请求发布到
https://energydevdealswebservices20160719041846.azurewebsites.net/Deals/SetDealFlag?deadid=3&flagValueToSet=trueurl,而不是将数据作为内容发送到https://energydevdealswebservices20160719041846.azurewebsites.net/Deals/SetDealFlag?
标签: c# asp.net asp.net-mvc curl asp.net-web-api