首页 > 解决方案 > 需要将 URL 参数传递给 Web API

问题描述

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

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-mvcasp.net-web-api

解决方案


尝试添加*到路由模板:

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

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


推荐阅读