1

由于您无法在大多数托管站点上使用 Put 和 Delete,因此我正在尝试创建一条避免使用这些站点的路线,但我无法使其正常工作..

我想要这样的路线

api/someController/Add/someInt

使用这个 RESTsharp 代码

private RestClient client;

public RESTful()
    {
        client = new RestClient
        {
            CookieContainer = new CookieContainer(),
            BaseUrl = "http://localhost:6564/api/",
            //BaseUrl = "http://localhost:21688/api/",
            //BaseUrl = "http://madsskipper.dk/api/"
        };
    }

    public void AddFriend(int userId)
    {
        client.Authenticator = GetAuth();

        RestRequest request = new RestRequest(Method.POST)
        {
            RequestFormat = DataFormat.Json,
            Resource = "Friends/Add/{userId}"
        };

        request.AddParameter("userId", userId);

        client.PostAsync(request, (response, ds) =>
        {
        });
    }

在我的 FriendsController 中点击这个方法

// POST /api/friends/add/Id
[HttpPost] //Is this necesary?
public void Add(int id)
{         
}

所以我在我的路线配置中添加了这个

    routes.MapHttpRoute(
    name: "ApiAdd",
    routeTemplate: "api/{controller}/Add/{id}",
    defaults: new { id = RouteParameter.Optional }
);

但是当我这样做时,我只点击了我的 FriensController 的构造函数而不是 Add 方法

编辑:

还尝试制作此路线配置

    routes.MapHttpRoute(
        name: "ApiAdd",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { action = "Add", id = RouteParameter.Optional }
    );

但同样的结果,控制器被击中而不是动作


解决方案:发现参数是用RESTsharp错误添加的,所以代替

    RestRequest request = new RestRequest(Method.POST)
    {
        RequestFormat = DataFormat.Json,
        Resource = "Friends/Add/{userId}"
    };

    request.AddParameter("userId", userId);

它应该是

        RestRequest request = new RestRequest(Method.POST)
        {
            RequestFormat = DataFormat.Json,
            Resource = "Friends/Add/{userId}"
        };

        request.AddUrlSegment("userId", userId.ToString());
4

1 回答 1

2

您可以在 Api 路由定义中包含操作名称:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

然后有这个动作:

[HttpPost]
public void Add(int id)
{

}

/api/friends/add/123现在您可以触发对url的 POST 请求。

The [HttpPost] attribute ensures that this action can only be invoked using the POST verb. If you remove it you could still invoke it through GET, but that's something you shouldn't do with actions that potentially modify state on the server.

于 2012-07-20T06:07:52.047 回答