簡體   English   中英

使用jQuery在ASP.NET MVC 5應用程序中調用WebAPI服務

[英]Calling WebAPI Service in ASP.NET MVC 5 application, using jQuery

我正在嘗試構建一個簡單的WebApi服務,該服務將實時返回帖子的評論。 因此,該服務僅實現了Get方法,並且它是傳遞的Post ID的字符串的IEnumerable的簡單返回:

 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);
}

在簡單的局部視圖中,我試圖每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教程嗎?

PS當我直接使用以下方法從瀏覽器中調用WebApi Get方法時:... / api / CommentApi / id route服務被調用並返回傳遞的post id的注釋,因此該服務還可以,我沒有在其中調用它很好的代碼...

首先,就像您自己說的那樣,當您在瀏覽器中鍵入URL並按Enter鍵時,您會收到來自Web API的響應:這意味着Web API服務和服務器已正確配置。 因此,您的問題與配置無關:問題在於請求本身。

網址和方法

為了使請求生效,它必須是GET請求,正確的URL和正確的參數。

您的路由模板看起來像如下routeTemplate: "api/{controller}/{id}"帶有可選的id 您的方法是一種get方法。 在這種方法中,可以從路由(模板中的{id}段)或查詢字符串中恢復參數,即:

  • GET api/CommentApi/5
  • GET api/CommentApi?id=5

您可以使用任何一個URL。

返回的數據格式和Accept標頭

Web API可以兩種不同的格式(XML或JSON)返回數據。 如果未指定任何內容,則返回的數據將采用XML格式(這就是在瀏覽器中鍵入URL時得到的信息)。 如果您喜歡JSON(在這種情況下),則需要在請求中添加標頭: Accept: application/json

注意:指定Content-Type沒有意義,因為您無法在GET請求中發送有效載荷(主體中的數據)

用jQuery做到這一點

從Web API服務中的GET方法獲取數據的最簡單方法是使用jQuery .getJSON 如果您查看文檔,您會發現此方法等效於

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

而且,如果您閱讀了.ajax()的文檔,您將了解指定dataType: "json"等同於包含標頭Accept:application/json ,該標頭要求Web API返回JSON數據。 您還將了解默認方法是GET。 因此,您必須確保的唯一一件事就是URL看起來像預期的那樣。 查看getJSON的簽名: jQuery.getJSON( url [, data ] [, success ] )

它需要一個URL和可選的數據以及一個成功的回調。 我建議不要使用回調,因此讓我們來看兩個發出請求的可能選項:

  • $.getJSON('/api/CommentApi/'+id)會呈現類似/api/CommentApi/5的URL(未指定數據)
  • $.getJSON('/api/CommentApi',{id:5})會呈現類似/api/CommentApi?id=5的URL(指定為JavaScript對象的數據,其屬性名稱類似於操作的參數名稱: id in this案件)

使用回應

我建議不要使用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);                                        
    });
};

您需要設置dataTypecontentType ,還需要在dataType傳遞id參數;

請嘗試以下操作:

 $.ajax({
        url: "/api/CommentApi/Get",
        type: 'GET',
        data: { id: @Model[i].PostId },
        dataType: 'json',
        contentType: 'application/json',
        success: 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);                                                        }
    });

更新資料

好的,將其分解為一個更簡單的工作示例,以下將起作用。

javascript

    var urlString = "http://localhost/api/CommentApi/Get";

    $.ajax({
        url: urlString,
        type: 'GET',
        data: { id : 1},
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) { console.log(data); }
    });
</script>

讓您的控制器僅按以下方式返回硬編碼值:

// GET api/values
public IEnumerable<string> Get(int id)
{
    return new List<string>() { "one", "two" };
}

運行上面的命令,並測試將其輸出到控制台。

首先,您好,您似乎沒有調用該方法。 我找不到對“ showAllComments”函數的任何調用。 當我復制您的代碼並在聲明后才調用

 <script>
    $(document).ready(function () {

        var showAllComments = function () {
            // code
        };

        showAllComments();
    })
</script>

我看到調用了ApiController方法,為我更新了html。 確定要調用“ showAllComments”功能嗎?

而且JotaBe的答案很好,應該可以。 並遵循JotaBe所寫的setTimeout函數。 請參見功能說明。

http://www.w3schools.com/jsref/met_win_setinterval.asp http://www.w3schools.com/jsref/met_win_settimeout.asp

您是否查看了呼叫的路由以及真正的服務器響應是什么?

您可能希望將Route屬性設置到操作上,然后看一下使用Postman快速調用它以查看響應。 我發現沒有使用郵遞員,這會使檢查路由變得比所需困難得多。

示例項似乎只是將根稱為/ api / comments / 1或api / comments /?id = 1,其中,從路由中獲取的調用看起來是/ api / comments / get?id = 1,這與IIRC默認路由一樣具有索引未獲取或查看的操作。

稍后,我可以啟動演示項目並測試正在發生的事情時,我將對其進行詳細介紹。

編輯:如果您將屬性添加到控制器/操作,您可以看到構造調用的方式更簡單一些:

[RoutePrefix("api/Account")]
public class AccountController : BaseAPIController
{
       [Route("someroute")]
       [HttpGet]
       public int mymethod(int ID){return 1;}
}

在此示例中,您將調用get到/ api / account / soumeroute?id = 123123並獲得1的返還。 HTTPGet只是一個幫助分離代碼可讀性的幫助(如果啟用了XMLAPI文檔,那么很高興)

t您是否嘗試添加以下內容:

dataType: 'json',
async: true,
type: 'GET', //EDIT: my mistake should be GET, thx JotaBe for pointing that

您的$ .ajax電話?

或嘗試這種方式:

$.ajax({
                url: "/api/CommentApi/" + "@Model[i].PostId.ToString()",

                dataType: 'json',
                async: true,
                type: 'GET',
                error: function () {
                    alert('Error');
                }

            success: function (data) {
                alert('Success')
            }});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM