首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AttributeRouting必选参数

AttributeRouting必选参数
EN

Stack Overflow用户
提问于 2013-08-01 23:11:39
回答 1查看 199关注 0票数 0

我可以给所有的控制器添加强制参数吗?我开发apikey接口,所以我想对每条路由都需要特殊的“RESTful”参数。

代码语言:javascript
运行
复制
        [HttpPut]
    [PUT("create")]
    public PostDto Create(string title, string description, string tag, long photo, float lat, float lon, int error)
    {
        if (description.Length > DescriptionMaxLength)
            throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength));

        throw new NotImplementedException();
    }

    [HttpPost]
    [POST("edit/{id:int}")]
    public bool Edit(int id, string title, string description, int? photo)
    {
        if (description.Length > DescriptionMaxLength)
            throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength));

        throw new NotImplementedException();
    }

    [HttpDelete]
    [DELETE("delete/{id:int}")]
    public bool Delete(int id)
    {
        if (id < 0)
            throw new ApiException(ErrorList.InvalidValue, "id is smaller than 0");

        throw new NotImplementedException();
    }

但我不想为每种方法都手动完成。

EN

回答 1

Stack Overflow用户

发布于 2013-08-03 02:50:09

首先,您需要确定在操作主体内检索API密钥的确切方式。由于您不希望将其作为方法的参数传递,因此它可以是控制器的属性(这不是实现此目的的最佳方法,您必须创建一个自定义的基本控制器类,但它可能适用于简单的场景)或另一个针对每个请求的临时存储。

然后,您需要创建一个Web API操作过滤器。它类似于常规的ASP.NET MVC操作过滤器,网上有大量的教程,但大多数都是关于授权的。

此筛选器将尝试将请求中的API注入控制器或您选择的临时存储-在筛选器的OnActionExecuting method中,您可以访问请求信息和控制器上下文。

当一切完成后,只需在Web API配置中注册您的过滤器,这里有一个关于如何做到这一点的example

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17997888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档