FanAs
FanAs

Reputation: 199

AttributeRouting mandatory parameter

Can I add mandatory parameter to all controller? I develop RESTful api, so I want to require special "apikey" parameter for every route.

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

But I don't want to do it manually for every method.

Upvotes: 0

Views: 208

Answers (1)

Andrew Khmylov
Andrew Khmylov

Reputation: 762

First of all, you need to determine the exact way you are going to retrieve the API key inside the action's body. Since you don't want to pass it as the method's argument, it can be a property of the controller (not the best way to do this, you have to create a custom base controller class, but it may work for the simple scenarios) or another temporary per-request storage.

Then you need to create a Web API action filter. It's similar to the regular ASP.NET MVC action filters, there are plenty of tutorials over the web, most of them are about the authorization though.

This filter will try to inject the API key from the request into the controller or the temporary storage of your choice - inside the filter's OnActionExecuting method you have an access to both the request info and the controller context.

When it's all done, just register your filter in the Web API config, here is an example on how to do this.

Upvotes: 1

Related Questions