无效的URI:在指定带有端口号的URL时,在C#中指定的端口无效,如http:// localhost:8080 / jasperserver / rest

问题描述 投票:3回答:4

我创建了一个简单的函数来执行Http PUT请求 -

public string checkIfUserExists(string userName)
    {
        var endPoint = new Uri("http://localhost:8080/jasperserver/rest_v2/users/"+userName);

        var request = (HttpWebRequest)WebRequest.Create(endPoint);
        request.Method = "PUT";
        request.ContentType = "urlencoded";

        var response = (HttpWebResponse)request.GetResponse();

        return "Success";
    }

当我执行此操作时,我得到一个异常“无效的URI:指定了无效的端口” -

var endPoint = new Uri("http://localhost:8080/jasperserver/rest_v2/users/"+userName);

有什么想法解决这个问题?是localhost的问题:网址的8080部分?

c# http-request
4个回答
1
投票

看看这个问题Invalid URI: Invalid port specified when url has more than one colon

您是否检查过用户名是否存在可能导致问题的字符?

评论后编辑 - 我引用此问题的原因是因为发生'无效端口'错误不是因为实际端口错误,而是因为URL中的其他无效字符。验证用户名是否已正确编码可以防止出现此问题。

var endPoint = new Uri("http://localhost:8080/jasperserver/rest_v2/users/" 
      + HttpUtility.UrlEncode(userName));

1
投票

我使用string.Concat()方法修复了这个错误: -

var endPoint = new Uri(string.Concat("http://localhost:8080/jasperserver/rest_v2/users/", userName));

0
投票

在将其连接到URL之前,请确保在userName参数上使用类似https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode%28v=vs.110%29.aspx的内容。


0
投票

我正面临着这个问题,并发现这是我的疏忽导致了这个问题。我在创建HttpRequestMessage实例时遇到了问题,如下所示。

var request = new HttpRequestMessage(new HttpMethod("PUT"), 
                    $"{_nextcloudConfigurationProvider.NextcloudBaseUrl}{FileConstants.ApiUploadFile.Replace("{UserName}", UserName)}");

enter image description here

问题是我在第二次常数之前错过了一个斜线“/”。这是remote.php/dav/files/{UserName}/{directoryName}/而不是/remote.php/dav/files/{UserName}/{directoryName}/。添加斜杠为我解决了问题。

只是为那些想念傻事的人分享这个,就像我一样。

© www.soinside.com 2019 - 2024. All rights reserved.