在JavaScript中维护WebAPI端点

时间:2016-03-21 13:50:16

标签: javascript asp.net-web-api asp.net-web-api2

我想知道是否有任何好的技巧可以让您的WebAPI控制器路由与客户端保持同步。

例如,您有一个WebAPI控制器BooksController。在客户端上,您可以通过调用端点来调用方法:

$.get('books/1');

然后有一天您决定重命名控制器,或添加RoutePrefix。这会破坏客户端代码,因为端点已更改。

我遇到了图书馆WebApiProxy,看起来很有趣。有没有人有解决这个问题的好方法?是否有理由在我可能忽略的客户端上使用字符串文字?

2 个答案:

答案 0 :(得分:1)

我创建了一个关于te主题的博客。看看:)

http://blog.walden.dk/post/2017/02/02/export-all-your-asp-net-webapi-endpoints-to-json

我正在研究一个在javascript中使用它的帖子。无论如何,这段代码导出了端点运行时,并将在重构和路由更改上工作。它还导出uri参数,它们可以用于在javascript中解析并替换为客户端的值。

实现您想要的最简单方法是在ASP.NET WEBAPI中使用内置的ApiExplorer。它搜索所有“ApiController”实现,并读取路由属性元数据。

public class EndpointManager
{
    public IEnumerable<ApiMethodModel> Export()
    {
        //Use the build-in apiexplorer to find webapi endpoints
        IApiExplorer apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
        //exclude endpoints without the attribute
        var apiMethods = apiExplorer.ApiDescriptions.Select(ad => new ApiMethodModel(ad)).ToList();
        return apiMethods;
    }
}

您可以创建返回生成数据的端点。

[RoutePrefix("api/endpoint")]
public class EndpointApiController : ApiController {
 [HttpGet]
    [Route("all")]
    public IEnumerable<ApiMethodModel> All()
    {
        var endpoints = new EndpointManager().Export();
        return endpoints;
    }
}

现在可以通过“/ api / endpoint / all”

访问所有端点

答案 1 :(得分:0)

以下是我在对您的问题的评论中谈到的一个示例:

&#13;
&#13;
function getUrl(uri) {
  var bookRoute = /books(.*?)/i;
  var otherRoute = /something(.*?)/i;
  
  if(uri.match(bookRoute)) {
    return uri.replace(bookRoute, "http://localhost/webapi/books$1")
  }
  
  if(uri.match(otherRoute)) {
    return uri.replace(otherRoute, "http://mydomain/api/something$1")
  }
  
  return uri;
}

alert(getUrl("books/1"));
alert(getUrl("something/realy/different/1"));
&#13;
&#13;
&#13;

您只需要在函数体中定义路径。