Friday, April 17, 2015

Web API UrlHelper (DefaultApi)

I wrote a helper to get the location to return in the Location header of an Add/Create request.  At first I wrote this (because I found it on the Internet so it has to be true, right?):

   1:  var urlHelper = new UrlHelper(request);
   2:  var uri = urlHelper.Route("DefaultApi", new { id });
   3:  return uri != null ? new Uri(uri, UriKind.Relative) : null;

The problem with that was that my Location header was being returned with the Add endpoint, which is obviously not right:

Location: /api/grade/add/1

To fix this, I created a new route in the WebApiConfig and then switched one line of code to use the new route:


   1:  config.Routes.MapHttpRoute(
   2:      name: "GetApi",
   3:      routeTemplate: "api/{controller}/get/{id}",
   4:      defaults: new { action = "Get", id = RouteParameter.Optional }
   5:  );


   1:  var urlHelper = new UrlHelper(request);
   2:  var uri = urlHelper.Route("GetApi", new { id });
   3:  return uri != null ? new Uri(uri, UriKind.Relative) : null;

That does it.  Now my header is right:

Location: /api/grade/get/1

No comments:

Post a Comment