0

我在构建一个新的 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;
}

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

{
    "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."
}

我已经尝试通过提琴手执行该操作,但看起来 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 
});

附加信息:使用提琴手进行测试时,我正在编写自己的请求,如下所示:

请求标头:用户代理:提琴手主机:localhost:50393 内容长度:29 内容类型:应用程序/json;字符集=utf-8

请求正文:{"id":1,"groups":[1,2,3,4,5]}

4

1 回答 1

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

通过 Fiddler 发送的 JSON 对象:

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

在 Fiddler 的 Headers 部分中,确保为您的方案添加此标头:

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

然后是 POST URL

http://localhost/api/Authentication/Subscribe

希望这可以帮助。

于 2013-10-03T11:58:27.900 回答