如何使用Web API中的属性路由通过URI发送数组? [英] How to send an array via a URI using Attribute Routing in Web API?

查看:131
本文介绍了如何使用Web API中的属性路由通过URI发送数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注有关Web API 2中属性路由的文章,尝试通过URI发送数组:

I'm following the article on Attribute Routing in Web API 2 to try to send an array via URI:

[HttpPost("api/set/copy/{ids}")]
public HttpResponseMessage CopySet([FromUri]int[] ids)

这在使用基于约定的路由时有效:

This was working when using convention-based routing:

http://localhost:24144/api/set/copy/?ids=1&ids=2&ids=3

但是使用属性路由,它不再起作用-我找不到404。

But with attribute routing it is no longer working - I get 404 not found.

如果我尝试这样做:

http://localhost:24144/api/set/copy/1

然后它起作用了-我得到一个包含一个元素的数组。

Then it works - I get an array with one element.

如何以这种方式使用属性路由?

How do I use attribute routing in this manner?

推荐答案

您注意到的行为与动作选择和模型绑定而不是属性路由。

The behavior you are noticing is more related to Action selection & Model binding rather than Attribute Routing.

如果您希望 ids来自查询字符串,请按如下所示修改路由模板(因为定义方式)使'ids在uri路径中成为必需项):

If you are expecting 'ids' to come from query string, then modify your route template like below(because the way you have defined it makes 'ids' mandatory in the uri path):

[HttpPost("api/set/copy")]

看看第二个问题,您是否想接受uri本身的ID列表,例如 api / set / copy / [1,2,3] ?如果是,我认为Web api不对这种模型绑定提供内置支持。

Looking at your second question, are you looking to accept a list of ids within the uri itself, like api/set/copy/[1,2,3]? if yes, I do not think web api has in-built support for this kind of model binding.

您可以实现如下所示的自定义参数绑定来实现此目的(我想还有其他更好的方法,例如通过modelbinders和值提供者来实现这一点,但我是不太了解它们...所以您可能也需要探索这些选项):

You could implement a custom parameter binding like below to achieve it though(I am guessing there are other better ways to achieve this like via modelbinders and value providers, but i am not much aware of them...so you could probably need to explore those options too):

[HttpPost("api/set/copy/{ids}")]
public HttpResponseMessage CopySet([CustomParamBinding]int[] ids)






示例:


Example:

[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)]
public class CustomParamBindingAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor paramDesc)
    {
        return new CustomParamBinding(paramDesc);
    }
}

public class CustomParamBinding : HttpParameterBinding
{
    public CustomParamBinding(HttpParameterDescriptor paramDesc) : base(paramDesc) { }

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

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, 
                                                    CancellationToken cancellationToken)
    {
        //TODO: VALIDATION & ERROR CHECKS
        string idsAsString = actionContext.Request.GetRouteData().Values["ids"].ToString();

        idsAsString = idsAsString.Trim('[', ']');

        IEnumerable<string> ids = idsAsString.Split(',');
        ids = ids.Where(str => !string.IsNullOrEmpty(str));

        IEnumerable<int> idList = ids.Select(strId =>
            {
                if (string.IsNullOrEmpty(strId)) return -1;

                return Convert.ToInt32(strId);

            }).ToArray();

        SetValue(actionContext, idList);

        TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
        tcs.SetResult(null);
        return tcs.Task;
    }
}

这篇关于如何使用Web API中的属性路由通过URI发送数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆