2016-02-28 28 views
2

我擁有帶簡單控制器的Web Api應用程序。獲取方法工作正常,但我有一個問題與帖子並把請求。無法在MVC 6 Web Api應用程序中發佈任何數據

[Route("api/[controller]")] 
[EnableCors("AllowAll")] 
public class LessonController : Controller { 
    ... 
    [HttpPut("{id}")] 
    public void Put(int id, [FromBody] Lesson lesson) { 
     ... 
    } 
    .... 
} 

其中Lesson

public class Lesson { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Text { get; set; } 
    public string Description { get; set; } 
    public bool IsModerated { get; set; } 
    public int? PrevLessonId { get; set; } 
    public int? NextLessonId { get; set; } 
} 

所以我嘗試發送請求並沒有運氣,教訓是隻是默認初始化屬性的對象。我發出請求兩路:先用JS

$.ajax({ 
    type: "POST", 
    url: 'http://localhost:1822/api/lesson/1', 
    data: JSON.stringify({ 
     lesson: { 
     description: "Fourth lesson description", 
     isModerated: true, 
     name: "Fourth lesson", 
     nextLessonId: 5, 
     prevLessonId: 3, 
     text: "Fourth lesson text" 
    }}), 
    contentType: "application/json", 
    success: function (data) { 
     alert(data); 
    } 
}); 

與郵差:Postman screen

所以內容類型是正確的。任何人都可以告訴我有什麼問題嗎?

UPD: 我曾嘗試使用PostLesson模型,包含從LessonId所有屬性和身體與UpperCamelCase數據通過郵遞員發送的請求,但它並沒有解決我的問題。

+0

您的課程對象有一個ID。爲了實現模型綁定,對象需要完全匹配;這也適用於房產的資本化。 –

+0

不,這不是我的問題的解決方法,我創建了一個新課程「PostLesson」,其中所有字段都來自「Lesson」但是「Id」,並且它不能解決我的問題。 – user3272018

+0

您創建的新類是camelCase,屬性名稱的第一個字母小寫,就像您要發佈的正文內容一樣? –

回答

1

我已經解決了我自己的問題。事實上這個問題很簡單。 我們只需要傳遞Post方法,該方法的結構等於Lesson模型,而不指定參數名稱。所以,我的js代碼需要看起來像

$.ajax({ 
    type: "POST", 
    url: 'http://localhost:1822/api/lesson/1', 
    data: JSON.stringify({ 
     description: "Fourth lesson description", 
     isModerated: true, 
     name: "Fourth lesson", 
     nextLessonId: 5, 
     prevLessonId: 3, 
     text: "Fourth lesson text" 
    }), 
    contentType: "application/json", 
    success: function (data) { 
     alert(data); 
    } 
}); 

對於一些另外的信息看this link

相關問題