将长参数传递给ASP.NET WebAPI

5

我希望将网站参数传递给Webapi,但它没有起作用。

Webapiconfig:

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

Web API控制器:接收参数并返回其他网站的HTML快照。
    [HttpGet]
    [Route("api/snapshot/{param}")]
    public string GetSnapShot(string param)
    {

        string fragment = param;
        string content = "";

        if (fragment != null)
        {
            int firstSlash = fragment.IndexOf("/");
            if (firstSlash <= 2)
                fragment = fragment.Substring(firstSlash + 1, fragment.Length - firstSlash - 1);
            using (IWebDriver driver = new PhantomJSDriver())
            {
                string url = String.Format("http://domain.com/{0}", fragment);
                driver.Navigate().GoToUrl(url);

                content = driver.PageSource;
            }
        }
        return content;
    }

如果我尝试访问api/snapshot/du-lieu,控制器可以正常工作,但如果我传递一个更复杂的参数,比如api/snapshot/%2Fdu-lieu%2Fbong-da-y-Serie-A%2Fseason%2F1%2Ftong-quan,它就无法工作,会返回404错误。请给予建议。
2个回答

1

为什么不将参数放入查询字符串中?这样你的代码会变成:

[HttpGet]
[Route("api/snapshot")]
public string GetSnapShot(string param1,string param2,string param3)
{
} 

无论你从哪里调用API,都要创建请求URL:http://<whatever domain you use>/api/snapshot?param1=valueparam1&param2=valueparam2&param3=valueparam3。请保留HTML标记。

不,我只想要一个唯一的参数,因为其他网站将传递动态参数,我的WebAPI返回HTML快照。我已经完整更新了我的代码。 - nam vo
有没有任何错误信息或其他定义“不起作用”的东西? - Martin Valentino

0
  [HttpGet]
        [Route("api/snapshot/{*param}")]
        public string GetSnapShot(string param)
{

}

现在它可以工作了,谢谢大家。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接