Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - Construct url in view for Web Api with attribute routing

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

Example (from the msdn-blog):

[RoutePrefix("reviews")]
public class ReviewsController : ApiController
{
    // eg.: /reviews
    [Route]
    public IHttpActionResult Get() { ... }
    // eg.: /reviews/5
    [Route("{reviewId}")]
    public IHttpActionResult Show(int reviewId) { ... }
    // eg.: /reviews/5/edit
    [Route("{reviewId}/edit")]
    public IHttpActionResult Edit(int reviewId) { ... }
}

Now I want to construct "/reviews/edit" in my view, how can I do this?

I've tried creating a little extension method, but it requires me to give every route an actual "RouteName". Is there a method I can use (like in MVC) where I can just pass the controller and action?

@Url.Action("Edit", "Reviews)

The method I'm using now (with RouteName) also doesn't allow me to use integers as parameters (unless I pass a default value). If I do need to name all my routes, how can I create a route url, but pass my parameters in the "data"-portion of my request?

Current method:

public static string ResolveWebApiRoute(this UrlHelper urlHelper, string routeName, object routeValues = null)
{
    var newRouteValues = new RouteValueDictionary(routeValues);
    newRouteValues.Add("httproute", true);

    return urlHelper.RouteUrl(routeName, newRouteValues);
}

EDIT

When I used methods like Url.RouteUrl(new { controller = ..., action = ...}), It redirects directly to that action (e.g. new { controller = "Reviews", action = "Show"} --> /reviews/show, whilest I want it to redirect to /reviews/...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...