1

i'm new to WebAPI and had a few qeustion to custom method calling. So, im working with Entity Framework and created a WebAPI with basic CRUD methods. But now i want to add some custom methods, is it possible to call arrays as parameters? And when yes, how?

This is my method:

public void AddRoles(Guid userid, Guid[] roleids)

So how it is possible to call this method through webapi? I tryed it with

http://localhost:60690/api/MyController/AddRoles...

And is it possible to call void method? What is the response?

thanks and greetings, Joerg

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
Jörg Zeyn
  • 81
  • 8

2 Answers2

3
http://localhost:60690/api/MyController/AddRoles?userid=<user id guid here>&roleids=<guid1 here>&roleids=<guid2 here>...

As for the void method, of course it is possible, response will be with 200 code and empty body.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • and where is the userid in your example? – Jörg Zeyn May 29 '13 at 11:39
  • @JörgZeyn, just skipped it for space sake. Behind the dots in other words. Will it be better if I add it? – Andrei May 29 '13 at 11:40
  • just one last question: i think i got a routing problem now, he is always looking for `GetUserById(System.Guid)` instead of AddRoles. Here is my route config `config.Routes.MapHttpRoute( name: "CustomApiActions", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );` – Jörg Zeyn May 29 '13 at 11:47
  • @JörgZeyn, routing seems OK, most likely it just unable to find necessary action. Have you decorated the action (AddRoles that is) with `HttpGet` attribute? – Andrei May 29 '13 at 11:53
1

For GET you can refer to the following SO question:

How to pass an array of integers to ASP.NET Web API?

If you want to try to use POST then continue to read:

You should create a DTO for your parameters like such:

public class AddRoleModel
{
    Guid UserId { get; set; }
    Guid[] RoleIds { get; set; }
}

Change your method to accept accept POST and your new AddRoleModel DTO instead of the two different parameters like so:

[HttpPost]
public void AddRoles(AddRoleModel model)
{
   ...
}

And POST the json for that model to the method

json could look like this:

{    
    UserId: "{guid}",
    RoleIds: ["{some guid}", "{some other guid}"]
}
Community
  • 1
  • 1
BlakeH
  • 3,354
  • 2
  • 21
  • 31