Callum Linington
Callum Linington

Reputation: 14417

WepApi Route and RoutePrefix Confusion

I have this controller:

[Authorize(Roles = Roles.Administrator),
RoutePrefix("Api/Portal/User")]
public class UserController : ServiceApiController
{
    /// <summary>
    /// Gets all User associated with the Account
    /// </summary>
    /// <param name="accountId">
    /// The account id.
    /// </param>
    /// <returns>
    /// The <see cref="JsonResponse"/>.
    /// </returns>
    [Route("{accountId:guid}")]
    public JsonResponse<UserDto> Get(Guid accountId)
    {
        return new JsonResponse<UserDto>("Success", true);
    }
}

Is the Url below to hit this route correct?

/Api/Portal/User?accountId=5cbcec52-f417-48a2-a241-470e48518858

I'm using Fiddler to execute the GET request.

I'm getting a tad confused here. My routes are set up like this:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

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

Another question, my route prefix is Api/Portal/User and the User is going to remain constant as the actual controller, so can I replace with Api/Portal/[controller] or Api/Portal/{controller}

Upvotes: 0

Views: 466

Answers (1)

MichaelS
MichaelS

Reputation: 3831

With your configuration, the correct URL would be

/Api/Portal/User/5cbcec52-f417-48a2-a241-470e48518858

If you want to use the other Url, you have to change your controller method as follow:

[Route("{accountId:guid}")]
public JsonResponse<UserDto> Get([FromUri]Guid accountId)
{
    return new JsonResponse<UserDto>("Success", true);
}

The parameter attribute [FromUri] defines where the value is from.

Upvotes: 1

Related Questions