无法使用多个参数消耗MVC Web Api HttpPost修饰操作

时间:2013-10-02 19:15:52

标签: json asp.net-mvc-4 asp.net-web-api restkit-0.20

我在构建一个新的MVC WebApi项目时遇到了问题,我的帖子操作似乎没有正常工作。

我有以下行动:

//--
//-- POST: /api/groups/subscribe/1/groups
[HttpPost]
public GroupResponse Subscribe(int id, List<int> groups )
{
    var response = new GroupResponse();
    var manager = new UserManagement();

    try
    {
        response.Status = 1;

    var subscribedGroups = manager.GetSubscribedGroups(id).Select(g => g.GroupId).ToList();
    foreach (var subscribedGroup in subscribedGroups.Where(groups.Contains))
    {
        groups.Remove(subscribedGroup);
    }

    //-- group is a reserved word @ escapes this and treats it as a regular variable
    foreach (var @group in groups.Where(g => !manager.JoinGroup(id, g)))
    {
        response.Status = 2;
        response.ErrorMessage = Constants.SUBSCRIBE_FAIL;
    }
    }
    catch (Exception)
    {
        response.Status = 2;
        response.ErrorMessage = Constants.SUBSCRIBE_FAIL;
        return response;
    }

    return response;
}

当我尝试从rest kit中使用此操作时,我收到以下错误消息:

{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:50393/api/groups/subscribe'.",
    "MessageDetail":"No action was found on the controller 'Groups' that matches the request."
}

我已尝试通过fiddler执行操作但是看起来api忽略了我的数据被发送到api,这让我感到困惑。

当我尝试使用api时,如下所示:/ api / groups / subscribe?id = 1然后执行api操作,但是我无法传递所需的列表。

我还设置了尝试处理此问题的路线,但它似乎没有任何帮助:

config.Routes.MapHttpRoute(
    "subscribe",
    "api/groups/subscribe/{id}/{groups}",
    new { controller = "Groups", action = "Subscribe", id = RouteParameter.Optional, groups = RouteParameter.Optional 
});

其他信息: 当用fiddler测试时,我按照以下方式编写自己的请求:

请求标题: 用户代理:Fiddler 主持人:localhost:50393 内容长度:29 Content-Type:application / json;字符集= UTF-8

申请机构: { “ID”:1, “基团”:[1,2,3,4,5]}

1 个答案:

答案 0 :(得分:1)

你可以尝试这个,现在用fiddler进行测试。

控制器:

public class AuthenticationController : ApiController
{
    [AcceptVerbs("POST")]
    public void Subscribe(SubscribeClass data)
    {
        //Do your stuff here
        int id = data.id;
        List<int> groups = data.groups;
        //data contains values
    }

    public class SubscribeClass
    {
        public int id { get; set; }
        public List<int> groups { get; set; }
    }
}

WebApiConfig:

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "AuthenticateUser",
            routeTemplate: "{controller}/{action}",
            defaults: new { },
            constraints: new { controller = "Authentication", action = "Subscribe" }
        );
    }

JSON对象通过Fiddler发送:

{ "id": 1 , "groups": [1, 2, 3, 4, 5]  }

在Fiddler的Headers部分中,请确保为您的场景添加此标题:

Content-Type: application/json; charset=utf-8

然后是POST网址

http://localhost/api/Authentication/Subscribe

希望这有帮助。