8

使用标准路线:

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

通过这些操作:

public class ValuesController : ApiController
{
    // GET api/values
    public string GetAll()
    {
        return "all";
    }

    // GET api/values/5
    public string GetById(int id)
    {
        return "single";
    }

    // GET api/values?ids=1&ids=2
    public string GetByIds([FromUri] int[] ids)
    {
        return "multiple";
    }

并向/api/values发出请求,我得到了这个异常:

Multiple actions were found that match the request: 
System.String GetAll() on type MvcApplication4.Controllers.ValuesController
System.String GetByIds(Int32[]) on type MvcApplication4.Controllers.ValuesController

我一直在转动我的轮子试图找到解决这个问题的方法。我相信GetAllGetByIds操作在这里被认为是Multiple,但它们不是因为 GetByIds 具有不同的签名。

是否有不涉及添加{action}到路线的解决方法?

4

4 回答 4

6

感谢大家的意见和建议。在四处选择选项之后,我发现这样做的唯一方法是结合 GetAll 和 GetByIds 操作并切换 ids 的长度。

public class ValuesController : ApiController
{
    // GET api/values/5
    public string GetById(int id)
    {
        return "single";
    }

    // GET api/values
    // GET api/values?ids=1&ids=2
    public string GetByIds([FromUri] int[] ids)
    {
        switch (ids.Length)
        {
            case 0:
                return "all";

            default:
                return "multiple";
        }
    }
于 2013-04-18T13:25:20.480 回答
2

我们目前不支持绑定来自 Uri 的值集合。以下是与此相关的问题以及动作消歧问题:

http://aspnetwebstack.codeplex.com/workitem/322

不幸的是,我想不出与动作选择问题(没有'{action}')本身相关的解决方法,即使您使用如下自定义参数绑定解决了模型绑定到集合的问题:

public string GetByIds(int[] ids)
    {
        return "multiple";
    }
------------------------

config.ParameterBindingRules.Insert(0, typeof(int[]), (paramDesc) => new SampleParameterBinding(paramDesc));

-------------------------

public class SampleParameterBinding : HttpParameterBinding
{
    public SampleParameterBinding(HttpParameterDescriptor desc)
        : base(desc)
    {
    }

    public override bool WillReadBody
    {
        get
        {
            return false;
        }
    }

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        HttpRequestMessage currentRequest = actionContext.Request;

        NameValueCollection nvc = currentRequest.RequestUri.ParseQueryString();

        //TODO: ERROR CHECKS
        int[] ids = nvc["ids"].Split(',').Select(str => Int32.Parse(str)).ToArray();

        // Set the binding result here
        SetValue(actionContext, ids);

        // now, we can return a completed task with no result
        TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
        tcs.SetResult(default(AsyncVoid));
        return tcs.Task;
    }

    private struct AsyncVoid
    {
    }
}
于 2013-04-15T18:31:35.070 回答
2

我推荐属性路由:

[RoutePrefix("api")]
public class ValuesController : ApiController
{
    // GET api/values
    // GET api/values?ids=1&ids=2
    [Route("values")]
    public string GetCollection([FromUri] IList<int> ids)
    {
        if (ids == null)
        {
          return "all";
        }
        return "multiple";
    }

    // GET api/values/5
    [Route("values/{id:int}")]
    public string GetById(int id)
    {
        return "single";
    }
于 2014-07-11T04:08:03.443 回答
0
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
于 2013-12-05T03:20:56.553 回答