2015-11-13 174 views
4

POST EDITED低于有没有办法用WebAPI生成Url?

我们无法弄清楚从的WebAPI控制器的情况下使用时,为什么UrlHelper将返回空字符串。

我们已经完成了必要的调试,但我们无法找出为什么发生这种情况,RouteData中有路由,但似乎没有工作。

大多数情况下,我们使用RenderViewToString函数,该函数加载包含调用Url.RouteUrl(routeName)的视图。

已经尝试过的东西是创建一个自定义UrlHelper(但无济于事),并用UrlHelper(MVC/HTTP)进行调试。

属性路由与路线名称使用,随处可见。

用法示例代码:

public class WebApiController : BaseApiController 
    { 
     [HttpPost] 
     [ResponseType(typeof(string))] 
     [Route("cart/get/checkout", Name = "api.cart.get.checkout")] 
     public IHttpActionResult GetCheckOutShoppingCart([FromBody] string data) 
     { 
       return Ok(RenderViewToString("CartController", "_CheckOutCartPartial", new ShoppingCartModel(Auth.IsAuthenticated ? Auth.GetCustomer().DefaultShippingInfo.CountryId : 148) 
       { 
        AddInsurance = false, 
        InsuredShipping = insuredShipping, 
        CurrentDeliveryMethodId = deliveryMethodId, 
        CurrentPaymentMethodId = paymentMethodId 
       })); 
     } 
    } 

BaseApiController类:

public class BaseApiController : ApiController 
    { 
     public static string RenderViewToString(string controllerName, string viewName) 
     { 
      return RenderViewToString(controllerName, viewName, new Dictionary<string, object>()); 
     } 

     public static string RenderViewToString(string controllerName, string viewName, object model) 
     { 
      using (var writer = new StringWriter()) 
      { 
       var routeData = new RouteData(); 
       routeData.Values.Add("controller", controllerName); 
       var fakeControllerContext = 
        new ControllerContext(
         new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), 
          new HttpResponse(null))), routeData, new FakeController()); 
       var razorViewEngine = new RazorViewEngine(); 
       var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false); 
       var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, 
        new ViewDataDictionary(model), new TempDataDictionary(), writer); 
       razorViewResult.View.Render(viewContext, writer); 
       return writer.ToString(); 
      } 
     } 

     public static string RenderViewToString(string controllerName, string viewName, Dictionary<string, Object> data) 
     { 
      using (var writer = new StringWriter()) 
      { 
       var viewData = new ViewDataDictionary(); 
       foreach (var kv in data) 
       { 
        viewData[kv.Key] = kv.Value; 
       } 

       var routeData = new RouteData(); 
       routeData.Values.Add("controller", controllerName); 
       var fakeControllerContext = 
        new ControllerContext(
         new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), 
          new HttpResponse(null))), routeData, new FakeController()); 
       var razorViewEngine = new RazorViewEngine(); 
       var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false); 
       var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, viewData, 
        new TempDataDictionary(), writer); 
       razorViewResult.View.Render(viewContext, writer); 
       return writer.ToString(); 
      } 
     } 

     private class FakeController : ControllerBase 
     { 
      protected override void ExecuteCore() 
      { 
      } 
     } 
    } 

编辑

我们已经组建了一个类应在理论的工作,但它不。 RouteData具有集合中的MVC和API路由。

public static class Url 
    { 
     public static bool IsWebApiRequest() 
     { 
      return 
       HttpContext.Current.Request.RequestContext.HttpContext.CurrentHandler is 
        System.Web.Http.WebHost.HttpControllerHandler; 
     } 

     public static string RouteUrl(string routeName, object routeValues = null) 
     { 
      var url = String.Empty; 
      try 
      { 
       if (IsWebApiRequest()) 
       { 
        var helper = new System.Web.Http.Routing.UrlHelper(); 
        url = helper.Link(routeName, routeValues);    
       } 
       else 
       { 
        var helper = new System.Web.Mvc.UrlHelper(); 
        url = helper.RouteUrl(routeName, routeValues);    
       } 

       return url; 
      } 
      catch 
      { 
       return url; 
      } 
     } 

     public static string HttpRouteUrl(string routeName, object routeValues = null) 
     { 
      var url = String.Empty; 
      try 
      { 
       if (IsWebApiRequest()) 
       { 
        var helper = new System.Web.Http.Routing.UrlHelper(); 
        url = helper.Link(routeName, routeValues); 
       } 
       else 
       { 
        var helper = new System.Web.Mvc.UrlHelper(); 
        url = helper.HttpRouteUrl(routeName, routeValues); 
       } 

       return url; 
      } 
      catch 
      { 
       return url; 
      } 
     } 
    } 

回答

3

这个问题已经通过建立一个自定义UrlHelper类,看起来到RouteTable,然后返回替换为模式的URL解决。

public static class Link 
{ 
    public static string RouteUrl(string routeName, object routeValues = null) 
    { 
     var url = String.Empty; 
     try 
     { 
      var route = (Route)RouteTable.Routes[routeName]; 
      if (route == null) 
       return url; 

      url = "~/".AbsoluteUrl() + route.Url; 
      url = url.Replace("{culture}", System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.ToLower()); 

      if (routeValues == null) 
       return url; 

      var values = routeValues.GetType().GetProperties(); 
      Array.ForEach(values, pi => url = Regex.Replace(url, "{" + pi.Name + "}", pi.GetValue(routeValues, null).ToString())); 

      return url; 
     } 
     catch 
     { 
      var newUrl = RouteUrl("403"); 
      if(newUrl == String.Empty) 
       throw; 

      return newUrl; 
     } 
    } 

    public static string HttpRouteUrl(string routeName, object routeValues = null) 
    { 
     return RouteUrl(routeName, routeValues); 
    } 
} 
+0

伟大的实施,大大帮助我。 – BastanteCaro

1

尝试Uri.Link(routeName,对象)

var uri = Url.Link("api.cart.get.checkout", new { id = 1 }); 

如果属性名称的路由参数匹配这将注入给定对象的属性到路线。

+0

恐怕我们也试过这个,并且它不起作用,大多数url都是在布局文件中随时产生的。 Url.Link只能在WebApiController的上下文中使用。 – NullBy7e

1

WebApi不是MVC。尽管看起来非常相似,但它是一个完全不同的系统。

UrlHelper(即MVC)将查看MVC路由表,并忽略任何WebApi路由。

尝试创建难度较大的路线,本质上是将控制器和动作名称硬编码到视图中。 :-(

+0

我们已经检查了RouteData集合,它包含了MVC和API路线。 – NullBy7e

1

OK,根据您的意见,似乎你想打电话给你Url.RouteUrl(string routeName, object routeValues = null)Url.HttpRouteUrl(string routeName, object routeValues = null)从你的MVC layout.cshtml文件。

如果是这样的情况下,Url.IsWebApiRequest()将返回false因为layout.cshtml文件作为处理MVC请求,而不是部分的WebAPI才会处理。这将导致URL生成方法来使用,而不是收集的WebAPI MVC路由集合。

更改Url类因此RouteUrl始终构建WebAPI url,并且HttpRouteUrl仅构建MVC网址,然后在您的布局文件中使用基于您在特定上下文中需要哪种网址的适当方法。

public static class Url 
{ 
    public static bool IsWebApiRequest() 
    { 
     return 
      HttpContext.Current.Request.RequestContext.HttpContext.CurrentHandler is 
       System.Web.Http.WebHost.HttpControllerHandler; 
    } 

    public static string RouteUrl(string routeName, object routeValues = null) 
    { 
     var url = String.Empty; 
     try 
     { 
      var helper = new System.Web.Http.Routing.UrlHelper(); 
      return helper.Link(routeName, routeValues);    
     } 
     catch 
     { 
      return url; 
     } 
    } 

    public static string HttpRouteUrl(string routeName, object routeValues = null) 
    { 
     var url = String.Empty; 
     try 
     { 
      var helper = new System.Web.Mvc.UrlHelper(); 
      return helper.HttpRouteUrl(routeName, routeValues); 
     } 
     catch 
     { 
      return url; 
     } 
    } 
} 
相关问题