【问题标题】:Need to pass a URL parameter to web API需要将 URL 参数传递给 Web API
【发布时间】:2019-05-21 21:40:37
【问题描述】:

我有一个 MVC 应用程序,其中包含大多数 System.Web.MVC.Controller 类型的控制器。还有一个类型为 System.Web.Http.ApiController 的 Web API 控制器。

Web API 控制器有一个动作需要接受 URL 作为参数,如下所示:

[HttpGet]       
public HttpResponseMessage Image(string path)
{
    //download and return image using WebClient library
}

在视图上我想使用Image 类似的操作

<image src="/api/image/?path=/remote/relative/path/someimage.jpg" alt="some description" />

我正在使用以下路线模板:

config.Routes.MapHttpRoute(
    name: "api-image",
    routeTemplate: "/api/image/{path}",
    defaults: new { controller = "WebApiClient", action = "Image" }
);

Image 操作仅在 /api/image/someimage-1.jpg/api/image/someimage-2.jpg 之类的路径中调用

问题: Image 操作不会被像 /api/image/?path=/remote/relative/path/someimage.jpg 这样的长路径调用

如果我使用HttpUtility.UrlEncode 对长路径进行编码,它只会转到全局 Not Found 操作(通过 web.config 配置)。

但如果我不对其进行编码,则会引发“在路径中发现危险字符”异常。

我做错了什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    尝试在路由模板中添加*

    config.Routes.MapHttpRoute(
        name: "api-image",
        routeTemplate: "/api/image/{*path}",
        defaults: new { controller = "WebApiClient", action = "Image" }
    );
    

    并在没有编码的情况下使用它。

    【讨论】:

      猜你喜欢
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2019-03-14
      • 1970-01-01
      • 2013-07-20
      • 2019-05-14
      相关资源
      最近更新 更多