我正在尝试构建一个简单的 WebApi 服务,该服务将实时返回帖子的评论。所以该服务只实现了 Get 方法,它是一个简单的返回 IEnumerable 的字符串,用于传递的帖子 ID:
public class CommentApiController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get(int id)
{
return new ApplicationDbContext().Posts.First(x => x.PostId == id).CommentId.Select(x => x.CommentText).ToList();
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
我也制作了 WebApiConfig 类并指定了如下路由:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
在我的 Global.asax.cs 文件中,我添加了该路由的引用:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
在简单的部分 View 中,我试图每 8 秒调用一次此服务,这样帖子的评论就可以自己显示,而无需刷新页面,以检查是否有其他用户对帖子发表了评论。
@model List<StudentBookProject.Models.Post>
<table class="table table-striped">
@foreach (var item in Model)
{
if (item.ImagePost != null)
{
<tr class="info">
<td>@item.CurrentDate</td>
</tr>
<tr class="info">
<td>
|@Html.ActionLink("Delete", "Delete", new { id = item.PostId }) |
@Html.ActionLink("Comment", "AddComment", new { id = item.PostId }, new { @class = "comment" }) |
</td>
</tr>
<tr class="info">
<td>
<img src="data:image/png;base64,@Convert.ToBase64String(item.ImagePost, 0, item.ImagePost.Length)" width="620" />
</td>
</tr>
<tr>
<td>
@Html.Partial("~/Views/Posts/ListComment.cshtml", item.CommentId)
</td>
</tr>
}
if (item.FilePost != null)
{
<tr class="info">
<td>@item.CurrentDate</td>
</tr>
<tr class="info">
<td>
| @Html.ActionLink("Delete", "Delete", new { id = item.PostId }) |
@Html.ActionLink("Comment", "AddComment", new { id = item.PostId }, new { @class = "comment" }) |
</td>
</tr>
<tr class="info">
<td>
File attachment
</td>
</tr>
}
if (item.TextPost != "")
{
<tr class="info">
<td>@item.CurrentDate</td>
</tr>
<tr class="info">
<td>
| @Html.ActionLink("Edit", "Edit", new { id = item.PostId }, new { @class = "lnkEdit" }) |
@Html.ActionLink("Delete", "Delete", new { id = item.PostId }) |
@Html.ActionLink("Comment", "AddComment", new { id = item.PostId }, new { @class = "comment" }) |
</td>
</tr>
<tr class="info">
<td>
@item.TextPost
</td>
</tr>
}
}
</table>
@{
int i = 0;
while (i < Model.Count())
{
if (Model[i].ImagePost != null || Model[i].TextPost != null || Model[i].FilePost != null)
{
<script>
$(document).ready(function () {
var showAllComments = function () {
$.ajax({
url: "/api/CommentApi/" + "@Model[i].PostId.ToString()"
}).done(function (data) {
var html = "";
for (item in data) {
html += '<div>' + data[item] + '</div>';
}
var divID = "@("quote" + Model[i].PostId.ToString())"
$('#' + divID).html(html);
setInterval(function () {
showAllComments();
}, 8000);
});
};
})
</script>
}
++i;
}
}
我的服务没有被调用,至少没有以正确的方式调用,导致新评论仅在刷新页面后显示。我知道 WebApi,尤其是在这种情况下应该很容易实现并且非常简单,但我对这项技术完全陌生,我不知道我错过了什么或错误地实现了什么。 一直试图找到一些合适的教程来帮助我解决这个问题,但还没有任何帮助。
我在某处读到我应该在 WebDAV 的 Web.config 文件中添加一行,但这对我也没有帮助。
<handlers>
<remove name="WebDAV"/>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
是否有人看到我没有做的事情以及可能在哪里出错?另外,有人知道一些不错的 .NET WebApi 教程吗?
附言当我使用以下方法直接从浏览器调用 WebApi Get 方法时: .../api/CommentApi/id 路由服务被调用并为传递的帖子 ID 返回评论,所以服务没问题,我不是在调用它以一种好的方式编写代码...
请您参考如下方法:
首先,正如您自己所说,当您在浏览器中键入 URL 并按下回车键时,您会收到来自 Web API 的响应:这意味着 Web API 服务和服务器已正确配置。所以你的问题与配置无关:问题出在请求本身。
网址和方法
要使请求生效,它必须是一个 GET 请求,指向正确的 URL,并带有正确的参数。
您的路线模板看起来像这样 routeTemplate: "api/{controller}/{id}" 带有可选的 id。您的方法是 get 方法。在这种方法中,参数可以从路由(模板中的 {id} 段)或查询字符串中恢复,即:
获取 api/CommentApi/5GET api/CommentApi?id=5
您可以使用这些 URL 中的任何一个。
返回数据格式和Accept header
Web API 可以返回两种不同格式的数据,XML 或 JSON。如果您未指定任何内容,返回的数据将采用 XML 格式(这就是您在浏览器中键入 URL 时得到的结果)。如果您更喜欢 JSON,它是 在这种情况下,您需要在请求中添加 header :Accept: application/json
注意:指定 Content-Type 没有意义,因为您不能在 GET 请求中发送负载(正文中的数据)
用 jQuery 实现
从 Web API 服务中的 GET 方法获取数据的最简单方法是使用 jQuery .getJSON .如果您查看文档,您会发现此方法等同于
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
而且,如果您阅读了有关 .ajax() 的文档,您就会明白指定 dataType: "json" 等同于包含 header Accept:application/json,要求Web API返回JSON数据。您还会了解到默认方法是 GET。因此,您必须确保的唯一另一件事是 URL 看起来符合预期。查看getJSON的签名:jQuery.getJSON( url [, data ] [, success ] )
它需要一个 URL 和可选的数据以及一个成功回调。我建议不要使用回调,所以让我们看看发出请求的 2 个可能选项:
$.getJSON('/api/CommentApi/'+id)将呈现类似/api/CommentApi/5的 URL(未指定数据)<$.getJSON('/api/CommentApi',{id:5})会呈现一个类似/api/CommentApi?id=5的 URL(数据指定为 JavaScript 对象,属性名称类似于操作的参数名称:在本例中为id)
使用响应
我建议不要使用 success 回调,而是使用 promise .done 方法。因此,无论您使用哪种语法进行调用,都必须像这样推迟 .done(就像您在原始代码中所做的那样):
$.getJSON('/api/CommentApi/'+id).done(function(response) {
// use here the response
});
最终代码
所以,修改后的 showAllComments 方法看起来像这样
请特别注意评论
var showAllComments = function () {
$.getJSON("/api/CommentApi/" + "@Model[i].PostId.ToString()")
.done(function (data) {
// create empty jQuery div
var $html = $('<div>');
// Fill the empty div with inner divs with the returned data
for (item in data) {
// using .text() is safer: if you include special symbols
// like < or > using .html() would break the HTML of the page
$html.append($('<div>').text(data[item]));
}
// Transfer the inner divs to the container div
var divID = "@("quote" + Model[i].PostId.ToString())";
$('#' + divID).html($html.children());
// recursive call to the same function, to keep refreshing
// you can refer to it by name, don't need to call it in a closure
// IMPORTANT: use setTimeout, not setInterval, as
// setInterval would call the function every 8 seconds!!
// So, in each execution of this method you'd bee asking to repeat
// the query every 8 seconds, and would get plenty of requests!!
// setTimeout calls it 8 seconds after getting each response,
// only once!!
setTimeout(showAllComments, 8000);
}).fail(function() {
// in case the request fails, do also trigger it again in seconds!
setTimeout(showAllComments, 8000);
});
};
