GUID的列表通过GET发送到MVC控制器的JSON在到达时为空,POST工作

Sea*_*son 2 c# ajax jquery json asp.net-mvc-3

我正在向我的MVC控制器发送一组类似GUID的对象,如下所示:

$.ajax({
    type: 'GET',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: {
        songIds: JSON.stringify(songIds)
    },
    success: function (data) {
    },
    error: function(error) {
        console.error(error);
    }
});
Run Code Online (Sandbox Code Playgroud)

我的请求标头中发送的数据如下所示:

songIds:[ "6cb44f55-9fd5-4540-9b11-75ccce816d67"]

我的MVC3控制器方法如下所示:

[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
    SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
    IList<Song> songs = songManager.GetByIds(songIds);
    return new JsonDataContractActionResult(songs);
}
Run Code Online (Sandbox Code Playgroud)

在这个实现中,我收到一个非null的List对象,但它总是为空.我的错是什么?

编辑:如果我像这样POST而不是GET它工作正常.怎么会??

$.ajax({
    type: 'POST',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        songIds: songIds
    }),
    success: function (data) {
        loadedSongs = loadedSongs;
        if (callback) {
            callback(data);
        }
    },
    error: function(error) {
        console.error(error);
    }
});
Run Code Online (Sandbox Code Playgroud)

dar*_*key 7

您应该尝试为您的jQuery Ajax请求使用"traditional"选项设置为true.

有关更多详细信息,请参阅文档:http://api.jquery.com/jQuery.ajax/

您还应该删除JSON.Stringify部分.

你可以尝试一下,让我知道它是否适合你?我在我的结尾做了一个测试,它运作得很好.

$.ajax({
    type: 'GET',
    url: 'http://localhost:61975/Song/GetByIds',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    traditional: true, //// traditional option to true
    data: {
       songIds: songIds  /// no JSON.stringify
    },
    success: function (data) {
    },
    error: function(error) {
      console.error(error);
    }
});
Run Code Online (Sandbox Code Playgroud)