我试图让这项工作失败。
我在API上使用AttributeRouting,我在WebAPI上定义了这个方法:
[POST("update"), JsonExceptionFilter]
public HttpResponseMessage PostUpdate([FromJson] long id, DateTime oriDt, string notes, int score)
当我尝试使用以下代码调用它时:
using (var httpClient = new HttpClient(CreateAuthorizingHandler(AuthorizationState)))
{
var args = new { id, oriDt, notes, score };
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("id", id.ToString()));
postData.Add(new KeyValuePair<string, string>("oriDt", oriDt.ToString(_dateService.DefaultDateFormatStringWithTime)));
postData.Add(new KeyValuePair<string, string>("notes ", notes));
postData.Add(new KeyValuePair<string, string>("score ", score.ToString(CultureInfo.InvariantCulture)));
var response = httpClient.PostAsJsonAsync(ApiRootUrl + "update", postData).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsAsync<bool>().Result;
return data;
}
return null;
}
响应总是404 - not found
。我在这里错过了什么?我尝试在代码中使用名为args
的匿名对象,但问题相同。
我也尝试了[FromJson]
属性以及相同的结果。
答案 0 :(得分:0)
首先,删除[FromJson]
。有了这个,你有这个行动方法。
public HttpResponseMessage PostUpdate(long id, DateTime oriDt,
string notes, int score)
如果您发布到下面的URI,它将起作用。
/更新/ 123 oridt = somedate&安培;笔记= somenote&安培;分值= 89
如果要使用请求正文来POST字段(就像使用客户端代码一样),请声明一个包含名称与请求正文中的字段相同的属性的类。
public class MyDto
{
public long Id { get; set; }
public DateTime OriDt { get; set; }
public string Notes { get; set; }
public int Score { get; set; }
}
然后改变这样的动作方法。
public HttpResponseMessage PostUpdate(MyDto dto)