【发布时间】:2016-06-16 01:11:30
【问题描述】:
我正在学习使用客户端创建 RESTful API,但在将用户输入传递给帖子时遇到了困难。我的控制器很好,因为我可以将数据发送到 db(使用 Swagger 测试),但在客户端,调试器在我的 PostAsJsonAsync 上给了我一个错误。我认为这可能与路由有关。这是我客户的邮政编码:
static async Task AddAsync(ForumPost fp)
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:7656/");
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
ForumPost thePost = new ForumPost() {
Subject = fp.Subject,
Message = fp.Message};
HttpResponseMessage response = await client.PostAsJsonAsync("post", thePost);
if (response.IsSuccessStatusCode)
{
Uri uri = response.Headers.Location;
Console.WriteLine("URI for new resource: " + uri.ToString());
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
以及控制器的相关位
[HttpPost]
// POST: api/Forum
[Route("post")]
public void PostNewMessage (string subject, string message)
{
if (ModelState.IsValid)
{
ForumPost p = new ForumPost(subject, message);
db.ForumPosts.Add(p);
db.SaveChanges();
}
}
我在 SO 上查看了各种不同但相似的问题,但很难理解。我曾尝试在路线中放置占位符,但也许我实施不正确? (如果这甚至是正确的思考方式!)如果有人可以帮助我解决这个问题,我将不胜感激。
【问题讨论】:
标签: c# api asp.net-web-api routes