我正在尝试使用TinyUrl制作一个网址速记器。问题是,我得到了以下错误:
System.Net.WebException: 'Error on the remote server: (400) Incorrect request.我已经尝试阅读几乎整个网站,但我没有找到解决办法。
控制器代码是:
namespace Prueba.Controllers
{
[HandleError]
public class TinyURLAPIController : Controller
{
// GET: TinyURLAPI
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View("Index");
}
[HttpPost]
public ActionResult MakeTinyUrl(string strURL)
{
var tinyUrl = WebRequest.Create("http: / tinyurl . com/api-create.php?url=" + strURL);
var shortUrl = tinyUrl.GetResponse();
using (var reader = new StreamReader(shortUrl.GetResponseStream())){
ViewData["tinyUrl"] = reader.ReadToEnd();
}
return PartialView("Index");
}
}
}这是索引代码:
<Html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<@Ajax.BeginForm("MakeTinyUrl", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "tinyUrl" }))>
@Html.TextBox("url")
<input id="btnMakeUrl" type="submit" value="Make tinyUrl" onclick="Index" />
</body>
</Html>我需要在文本框中输入长URL,然后按下按钮在标签中显示短URL
发布于 2019-08-02 13:01:23
我不能发表评论,所以我会把它写成一个答案!
您的问题不是api请求。您的strURL可能与我的代码一样为空。
尝试在您的观点中进行以下更改:
from
@Html.TextBox("url")
to
@Html.TextBox("strURL")而且,在定义表单时,html也不太有效。尝试:
@using (Ajax.BeginForm("MakeTinyUrl", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "tinyUrl" }))
{
@Html.TextBox("strURL")
<input id="btnMakeUrl" type="submit" value="Make tinyUrl" onclick="Index" />
}发布于 2019-08-02 12:50:49
在将值传递给视图之前,可能必须先对其进行UrlEncode:
https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.8
发布于 2019-08-02 13:40:05
据我所知,由于受到限制,您已经更改了帖子中的api链接。
首先,我会在您喜欢的浏览器中手动调用api,使用您要尝试shorten...make的URL,确定这是可以的。
例如[redacted]tinyurl.com/api-create.php?url=http://www.yoururltest.com
接下来,使用断点运行测试,逐步遍历代码,查看错误发生的确切位置,并查看控制器在请求中接收和使用的数据。
我敢打赌你会在路上的某个地方发现问题的
https://stackoverflow.com/questions/57326487
复制相似问题