0
[Route("api/advertisement/{brandID}/{advertisementID}")]
public class BaseApiController : ApiController
{
    public string AdvertisementID { get; private set; }
    public int BrandID { get; private set; }
    public BaseReportRepository ReportRepository { get; private set; }

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);

        var routeData = controllerContext.RouteData;

        this.AdvertisementID = routeData.Values["advertisementID"].ToString();
        this.BrandID = (int)routeData.Values["brandID"];

        this.ReportRepository = RepositoryFactory
            .CreateRepository(this.BrandID)
            .ReportRepository;
    }
}

why can not get the router data brandID

7
  • what do you have actually in that varaible null or empty string? Commented Jun 15, 2018 at 8:04
  • Also how do you call it? the URL you use. Commented Jun 15, 2018 at 8:05
  • @Prashant Pretty sure ApiController's Initialize method doesn't have an override including brandID and advertismentID. Commented Jun 15, 2018 at 8:07
  • get router data value "MS_SubRoutes"" Commented Jun 15, 2018 at 8:09
  • This seems relevant. Commented Jun 15, 2018 at 8:21

1 Answer 1

1

Something like this should solve your problem:

IHttpRouteData requestRouteData = controllerContext.Request.GetRouteData();
IEnumerable<IHttpRouteData> subroutes = (IEnumerable<IHttpRouteData>)requestRouteData.Values["MS_SubRoutes"];
IHttpRouteData routeData = subroutes.FirstOrDefault();
if (routeData != null)
{
    this.AdvertisementID = routeData.Values["advertisementID"].ToString();
    this.BrandID = int.Parse(routeData.Values["brandID"].ToString());
}

You should also constrain your brandID parameter:

[Route("api/advertisement/{brandID:int}/{advertisementID}")]

If you’re traversing the route collection in any way (e.g. in a ControllerSelector) it is important to understand where these routes actually are. When you use attribute routing, all the route attributes get added to a common route without a name. This is a special route that is an instance of an internal class called RouteCollectionRoute. This route has a collection of sub-routes that you can query for that includes all the attribute routes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.