在mvc4中为添加和删除创建通用路由



由于您不能在大多数托管网站上使用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的构造函数,而不是添加方法

编辑:

还尝试过将此路由配置为

    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());

您可以在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请求。

[HttpPost]属性确保只能使用POST谓词调用此操作。如果您删除了它,您仍然可以通过GET调用它,但对于可能修改服务器上状态的操作,您不应该这样做。

最新更新