将长参数传递给asp.net webapi

时间:2022-08-20 13:42:56

I'd like to pass a website parameter to a webapi, but it fails to work.

我想将一个网站参数传递给webapi,但它无法正常工作。

Webapiconfig:

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

Web api controller: take the param and return the htmlsnapshot of the other website

Web api控制器:获取参数并返回其他网站的htmlsnapshot

    [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;
    }

if I try api/snapshot/du-lieu -> hit the controller fine but if I pass in a more complicated like

如果我尝试api / snapshot / du-lieu - >打击控制器很好,但如果我传入更复杂的

api/snapshot/%2Fdu-lieu%2Fbong-da-y-Serie-A%2Fseason%2F1%2Ftong-quan -> fails to work, return 404

api / snapshot /%2Fdu-lieu%2Fbong-da-y-Serie-A%2Fseason%2F1%2Ftong-quan - >无效,返回404

Please advise.

2 个解决方案

#1


1  

Why dont you put your param into query string?? Your code will become

为什么不把你的param放入查询字符串?你的代码将成为

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

And from wherever you call the api, create the request url http://<whatever domain you use>/api/snapshot?param1=valueparam1&param2=valueparam2&param3=valueparam3

从您调用api的任何地方,创建请求URL http:// <您使用的域名 api snapshot?param1="valueparam1&param2" = valueparam2&param3="valueparam3

#2


0  

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

}

It works now, thanks all.

它现在有效,谢谢大家。

#1


1  

Why dont you put your param into query string?? Your code will become

为什么不把你的param放入查询字符串?你的代码将成为

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

And from wherever you call the api, create the request url http://<whatever domain you use>/api/snapshot?param1=valueparam1&param2=valueparam2&param3=valueparam3

从您调用api的任何地方,创建请求URL http:// <您使用的域名 api snapshot?param1="valueparam1&param2" = valueparam2&param3="valueparam3

#2


0  

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

}

It works now, thanks all.

它现在有效,谢谢大家。