Construct url in view for Web Api with attribute routing

后端 未结 3 1571
你的背包
你的背包 2020-12-19 02:58

How can I get the url from web api in my view?

Example (from the msdn-blog):

[RoutePrefix(\"reviews\")]
public class ReviewsController : ApiControlle         


        
相关标签:
3条回答
  • 2020-12-19 03:21

    Generating links to Web API routes always require a RouteName, so you should have something like below:

    [Route("{reviewId}/edit", Name="EditView")]
    public IHttpActionResult Edit(int reviewId) { ... }
    

    You can then generate a link like /reviews/1/editto Web API.

    Url.RouteUrl(routeName: "EditView", routeValues: new { httpRoute = true, reviewId = 1 });
    

    or

    Url.HttpRouteUrl(routeName: "EditView", routeValues: , reviewId = 1)
    

    Note that route names need to be specified explicitly and they are no longer generated automatically like what @Karhgath is suggesting. This was a change made from RC to RTM version.

    0 讨论(0)
  • 2020-12-19 03:32

    In WebApi2 when using AttributeRouting, route names are named by default Controller.Action, but you could specify a RouteName also:

    [RoutePrefix("reviews")]
    public class ReviewsController : Controller
    {
        // The route name is defaulted to "Reviews.Index" 
        [Route]
        public ActionResult Index() { ... }
    
        // The route name is "ShowReviewById"
        [Route("{reviewId}"), RouteName("ShowReviewById")]
        public ActionResult Show(int reviewId) { ... }
    
        // The route name is by default "Reviews.Edit"
        [Route("{reviewId}/edit")]
        public ActionResult Edit(int reviewId) { ... }
    

    Then to call it in the view you only need to set the route name and send the parameters as an anonymous object:

    // Outputs: /reviews/123
    @Url.Action("ShowReviewById", new { reviewId = 123 })
    // Outputs: /reviews/123/edit
    @Url.Action("Reviews.Edit", new { reviewId = 123 })
    
    0 讨论(0)
  • 2020-12-19 03:35

    When using route attributes I was able to get the route of a WebApi2 controller from an MVC view using something like this:

    Url.HttpRouteUrl("RouteName", new { })
    
    0 讨论(0)
提交回复
热议问题