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
839 views
in Technique[技术] by (71.8m points)

asp.net mvc - How do I generate a webapi url from an MVC view?

Based on How to create ASP.NET Web API Url?

Neither of these plus a few more combinations of them I've tried are working

 <li><a href="@Url.RouteUrl("DefaultApi",new {area=string.Empty,httproute = string.Empty, controller = "corpuserrequest", action="Get"})">CorpUser</a></li>
                        <li><a href="@Url.Action("Get","CorpUserRequest",new {area=string.Empty,httproute ="", controller = "CorpUserRequest", action="Get"})">CorpUser</a></li>

Here's my api config route table:

//https://stackoverflow.com/questions/11407267/multiple-httppost-method-in-mvc4-web-api-controller
        config.Routes.MapHttpRoute(
            name: "ApiReq",
            routeTemplate: "webapi/{controller}/{action}",
           defaults: null,
           constraints: new { action = "Req" }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new
            {
                id = @"^d*$",// Only integers 
                action = "^(?![rR]eq)$" //anything except req or Req
            }
        );

Why isn't the routing working? The RouteUrl returns empty string or null, the Action returns

<a href="http://localhost:11601/CorpUserRequest/Get">

instead of what the actual url should be http://localhost:11601/api/CorpUserRequest

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could use either of the following to generate links to Web API:

  1. @Url.HttpRouteUrl("DefaultApi", new {controller = "corpuserrequest"})
  2. @Url.RouteUrl("DefaultApi", new { httproute = true, controller = "corpuserrequest"})

Usually you would use option 1., but sometimes you might need to use 2. like in the following post (this post doesn't necessarily use RouteUrl, but the idea is that in places where you do not have a convenient extension like HttpRouteUrl, in this case Html.BeginForm, you can use httproute=true to indicate that you are indeed trying to generate a url to a Web API route)

ASP.Net WebApi: Invalid URL generated in BeginForm


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

...