0

我目前正在嘗試做一些應該相當直接的事情,但說實話,目前還差得遠,它讓我有點生氣。創建帖子後的web api 2動作

我一直在使用獲取操作在我的WebApi,但是我試圖創建發佈操作,以保持我的mvc控制器清潔,但我不能爲我的生活弄清楚爲什麼我的獲取操作工作預期,但我在一個404

using Microsoft.AspNet.Authorization; 
using Microsoft.AspNet.Mvc; 
using TamWeb.Models.api; 

namespace TamWeb.Controllers.api 
{ 
    [Authorize] 
    [Route("api/[controller]")] 
    public class AdminController : Controller 
    { 
     [HttpPost] 
     public bool UpdateDetails([FromBody]DetailsViewModel model) 
     { 
      return false; 
     } 
    } 
} 

using System; 

namespace TamWeb.Models.api 
{ 
    public class DetailsViewModel 
    { 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
    } 
} 

的API控制器後行動的結果很簡單,因爲它得到的按其他幾個API的問題,而不是使用字符串參數我創建了一個模型對象,並按照其他的答案,並與我可以找到幾個過時的文檔,我會按如下方式使用api:

$(function() { 
    var firstname = $('#firstName').val(); 
    var lastname = $('#lastName').val(); 

    $.ajax({ 
     url: "api/admin/UpdateDetails", 
     type: "POST", 
     data: JSON.stringify([firstname, lastname]), 
     success: function(data) { 
      console.log(data); 
     }, 
     error: function() { console.log("error") } 
    }); 
}); 

據我可以告訴一切「應該」的工作,然而小提琴手不斷告訴我的網址不存在,所以現在我不知道什麼是錯的。

+2

你試過w^ith'url:「api/admin」'? –

回答

0

希望我的回答能幫助你處理你的問題。
1。首先的問題,你必須使用「ApiController」代替「控制器」
2. [授權] < - 你必須得到令牌密鑰,然後用它來得到的WebAPI

數據如下代碼,我將分享你我簡單的代碼沒有授權,我希望它能夠解決您的問題 客戶端代碼

$("#read1").click(function() {  
     $.support.cors = true; 
     $.ajax({ 
      crossDomain: true, 
      url: 'http://localhost:43520/api/Banners/', 
      datatype: "json", 
      contenttype: "application/json; charset=utf-8", 
      data: { id: 123 }, 
      type: 'post',   
      error: function (xhr, status, errorThrow) { 
       alert(xhr.status); 
      }, 
      success: function (data) { 
       alert(JSON.stringify(data)); 
      } 
     }); 
    }); 

服務器代碼

// GET: api/Banners/5 
     [ResponseType(typeof(Banners))] 
     public IHttpActionResult GetBanners(int id) 
     { 
      Banners banners = db.Banners.Find(id); 
      if (banners == null) 
      { 
       return NotFound(); 
      } 

      return Ok(banners); 
     }