【问题标题】:Pass URL containing a query string as a parameter ASP.Net Web API GET?传递包含查询字符串的 URL 作为参数 ASP.Net Web API GET?
【发布时间】:2014-05-06 06:40:11
【问题描述】:

我正在尝试将 URL 作为字符串参数传递给 WEB API GET 方法。

控制器:

public class LinksController : ApiController
{
    public HttpResponseMessage Get(string targetUrl)
    {
        //query db with targetURL
    }
}

目的是查询数据库以查看是否存储了 URL。这适用于简单 URL 和查询字符串包含单个参数的 URL,例如:

我遇到的问题具体是查询字符串包含多个参数时,例如

调试时targetUrl的值只有“.../watch?v=nLPE4vhSBx4”,表示&feature=youtube_gdata丢失

GET 请求如下所示:

http://localhost:58056/api/links?targetUrl=http://www.youtube.com/watch? v=nLPE4vhSBx4&feature=youtube_gdata

我也尝试在 WebApiConfig.cs 中添加以下路由:

config.Routes.MapHttpRoute(
    name: "Links",
    routeTemplate: "api/links/{targetUrl}",
    defaults: new { controller = "Links", targetUrl= RouteParameter.Optional }
);

但是 GET 请求会导致 400 Bad Request。

所以我的问题是,不能这样做吗?我想要完整的网址!还是我需要更改方法标头以使用 [FromBody] 属性并将其作为 JSON 对象传递?

【问题讨论】:

    标签: asp.net-web-api url-parameters asp.net-web-api-routing


    【解决方案1】:

    你应该URLEncode你的目标URL参数,这样它就不会被误认为是后续的查询字符串参数。这意味着您指定的 URL 应显示为:

    http://localhost:58056/api/links?targetUrl=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnLPE4vhSBx4%26feature%3Dyoutube_gdata
    

    然后在您的 Get 方法中,URLDecode 作为参数传递的字符串。

    这两种方法都可以在System.Web.HttpUtility找到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 2010-12-25
      相关资源
      最近更新 更多