Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to create ASP.NET Web API Url?

In ASP.NET MVC, we have @Url.Action for actions. Is there something similar like @Url.Api which would route to /api/controller?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The ApiController has a property called Url which is of type System.Web.Http.Routing.UrlHelper which allows you to construct urls for api controllers.

Example:

public class ValuesController : ApiController
{
    // GET /api/values
    public IEnumerable<string> Get()
    {
        // returns /api/values/123
        string url = Url.Route("DefaultApi", new { controller = "values", id = "123" });
        return new string[] { "value1", "value2" };
    }

    // GET /api/values/5
    public string Get(int id)
    {
        return "value";
    }

    ...
}

This UrlHelper doesn't exist neither in your views nor in the standard controllers.


UPDATE:

And in order to do routing outside of an ApiController you could do the following:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string url = Url.RouteUrl(
            "DefaultApi", 
            new { httproute = "", controller = "values", id = "123" }
        );
        return View();
    }
}

or inside a view:

<script type="text/javascript">
    var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "values", id = "123" })';
    $.ajax({
       url: url,
       type: 'GET',
       success: function(result) {
           // ...
       }
    });
</script>

Notice the httproute = "" route token which is important.

Obviously this assumes that your Api route is called DefaultApi in your RegisterRoutes method in Global.asax:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...