如何创建的ASP.NET Web API的网址是什么? [英] How to create ASP.NET Web API Url?

查看:93
本文介绍了如何创建的ASP.NET Web API的网址是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC中,我们有 @ Url.Action 动作。是否有类似的东西像 @ Url.Api 这将路线/ API /控制器?

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

推荐答案

的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller%28v=vs.108%29.aspx\">ApiController有一个叫做物业<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.url%28v=vs.108%29.aspx\">Url这是类型<一的href=\"http://msdn.microsoft.com/en-us/library/system.web.http.routing.urlhelper%28v=vs.108%29.aspx\">System.Web.Http.Routing.UrlHelper它允许你建立网址API控制器。

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.

例如:

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";
    }

    ...
}

这UrlHelper不无论是在你的意见也不在标准控制器存在。

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

更新:

为了做一个ApiController你可以做以下的路由外:

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();
    }
}

或视图中:

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

注意 httproute =路线令牌这是非常重要的。

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

显然,这个假定你的API路由被称为 DefaultApi 在你的RegisterRoutes方法的Global.asax

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 }
);

这篇关于如何创建的ASP.NET Web API的网址是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆