asp.net-web-api - 为 ApiController 之外的 asp.net web api 中的资源生成 url

标签 asp.net-web-api

在asp.net web api 中寻找一种为特定资源构建或生成url 的方法。它可以在 Controller 中完成,因为它继承自 ApiController,因此您可以获得 UrlHelper。

我希望从 ApiController 的上下文中构建资源 url。

最佳答案

这是我所做的:

  • 需要 HttpContext/Request,因此可能无法在 Application_Start 中工作。
  • 仅在 WebApi 1 中测试
  • 仅适用于在 GlobalConfiguration 中注册的路由(但如果您有其他路由,只需将其传入)

  • // given HttpContext context, e.g. HttpContext.Current
    var request = new HttpRequestMessage(HttpMethod.Get, context.Request.Url) {
        Properties = {
            { HttpPropertyKeys.HttpConfigurationKey, GlobalConfiguration.Configuration },
            { HttpPropertyKeys.HttpRouteDataKey, new HttpRouteData(new HttpRoute()) },
            { "MS_HttpContext", new HttpContextWrapper(context) }
        }
    };
    
    var urlHelper = new UrlHelper(request);
    

    关于asp.net-web-api - 为 ApiController 之外的 asp.net web api 中的资源生成 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10490693/

    相关文章:

    javascript - Web API - 保留字?

    asp.net-mvc-4 - 在 ASP.NET Web Api 中自定义绑定(bind)

    c# - WebApi复杂类型uri/获取多个参数

    c# - task.run 异步方法中出现空引用错误

    c# - 初学者在这里 : How does my Repository Layer know which user is logged in?

    asp.net-web-api - Web API - 支持的动词吗?

    c# - 获取 TraceTelemetry 以显示在 Application Insights 时间线中

    asp.net-web-api - ASP.Net Web API帮助页面区域返回空输出

    c# - 为 ASP.NET Web API 中的单个请求更改 JsonFormatter

    c# - Web API 返回 XML