AttributeRouting icon indicating copy to clipboard operation
AttributeRouting copied to clipboard

How to get the path to a newly created resource via a POST using AttributeRouting

Open abpatel opened this issue 11 years ago • 2 comments

Is there a specific API call to get the location of a created resource via a POST. I have the following POST method.

         [POST("Products", RouteName = "PostProduct")]
         public HttpResponseMessage Post(Product item)
         {

           if (ModelState.IsValid)
           {
            this.productRepository.InsertOrUpdate(item);
            this.productRepository.Save();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, item);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = item.ID }));
            return response;
         }

Is there a way to set the response.Headers.Location by asking Attribubte routing to generate the path to the new resource? In the above code I am the "DefaultApi" route that Webapi generates to get the URL to the new resource but how can I do this if I do not want to use the "DefaultApi" route since this is redundant if I use attribute routing

abpatel avatar Apr 28 '13 02:04 abpatel

Figured it out: response.Headers.Location = new Uri(Url.Link("PostProduct", new { id = item.ID }));

But,if I remove the following "DefaultApi" route from RouteConfig.cs: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

how do I specify the default route so that when the app starts it loads the same Index view of the HomeController?

abpatel avatar Apr 28 '13 02:04 abpatel

[Thanks to Kiran Chala for this answer on so]

[RoutePrefix("")]
public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }
}

pjklein avatar Jun 17 '13 18:06 pjklein