在 C# Monodevelop 中创建 Uri 时出错
Error creating Uri in C# Monodevelop
我正在尝试做一个与 API REST 通信的桌面应用程序,然后我决定在我的 xubuntu 中使用 MonoDevelop 来做它。我尝试使用构造函数从字符串创建 Uri,但是当创建对象 Uri 时,它出现在我的 MonoDevelop 调试器中:
stationUri {System.Uri}
System.Uri AbsolutePath System.NullReferenceException: Object
reference not set to an instance of an object AbsoluteUri
System.NullReferenceException: Object reference not set to an
instance of an object Authority System.NullReferenceException:
Object reference not set to an instance of an object DnsSafeHost
System.NullReferenceException: Object reference not set to an
instance of an object Fragment System.NullReferenceException:
Object reference not set to an instance of an object Host
System.NullReferenceException: Object reference not set to an
instance of an object HostNameType System.NullReferenceException:
Object reference not set to an instance of an object
urlConParametros https://api.thingspeak.com/channels/***/fields/4.json?api_key=***&results=2
字符串
由于安全原因,我没有显示完整的 URL.
以及与此错误相关的相应代码:
public string GetResponse_GET(string url, Dictionary<string, string> parameters)
{
try
{
//Concatenamos los parametros, OJO: antes del primero debe estar el caracter "?"
string parametrosConcatenados = ConcatParams(parameters);
string urlConParametros = url + "?" + parametrosConcatenados;
string responseFromServer = null;
Uri stationUri = new Uri(urlConParametros);
if(!stationUri.IsWellFormedOriginalString())
{
System.Console.WriteLine("Url Vacía");
}
else
{
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(stationUri);
wr.Method = "GET";
wr.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream newStream;
// Obtiene la respuesta
System.Net.WebResponse response = wr.GetResponse();
// Stream con el contenido recibido del servidor
newStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
// Leemos el contenido
responseFromServer = reader.ReadToEnd();
// Cerramos los streams
reader.Close();
newStream.Close();
response.Close();
}
return responseFromServer;
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == 404)
throw new Exception("Servicio Remoto No Encontrado: " + url);
else throw ex;
}
}
private string ConcatParams(Dictionary<string, string> parameters)
{
bool FirstParam = true;
string Parametros = null;
if (parameters != null)
{
Parametros = "";
foreach (KeyValuePair<string, string> param in parameters)
{
if(!FirstParam)
Parametros+="&";
Parametros+= param.Key + "=" + param.Value;
FirstParam = false;
}
}
return Parametros == null ? String.Empty : Parametros.ToString();
}
如果我运行完全代码,抛出下一个stackTrace关联(我删除了敏感数据):
Exception in Gtk# callback delegate
Note: Applications can use GLib.ExceptionManager.UnhandledException to handle the exception.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object
at System.Net.WebRequest.Create (System.Uri requestUri) [0x00000] in :0
at MainWindow.GetResponse_GET (System.String url, System.Collections.Generic.Dictionary`2 parameters) [0x0002b] in /home//MonoDevelop Projects///MainWindow.cs:92
at MainWindow.showAct (System.Object sender, System.EventArgs e) [0x0003f] in /home//MonoDevelop Projects///MainWindow.cs:34
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in :0
--- End of inner exception stack trace ---
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00053] in :0
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0
at System.Delegate.DynamicInvokeImpl (System.Object[] args) [0x0010d] in :0
at System.MulticastDelegate.DynamicInvokeImpl (System.Object[] args) [0x0000b] in :0
at System.Delegate.DynamicInvoke (System.Object[] args) [0x00000] in :0
at GLib.Signal.ClosureInvokedCB (System.Object o, GLib.ClosureInvokedArgs args) [0x00067] in :0
at GLib.SignalClosure.Invoke (GLib.ClosureInvokedArgs args) [0x0000c] in :0
at GLib.SignalClosure.MarshalCallback (IntPtr raw_closure, IntPtr return_val, UInt32 n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data) [0x00086] in :0
at GLib.ExceptionManager.RaiseUnhandledException (System.Exception e, Boolean is_terminal) [0x00000] in :0
at GLib.SignalClosure.MarshalCallback (IntPtr raw_closure, IntPtr return_val, UInt32 n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data) [0x00000] in :0
at Gtk.Application.gtk_main () [0x00000] in :0
at Gtk.Application.Run () [0x00000] in :0
at .MainClass.Main (System.String[] args) [0x00012] in /home//MonoDevelop Projects///Program.cs:13
我不知道为什么不能从字符串中正确建立 Uri... 然后如果我传递不正确的 Uri 来创建 WebRequest
也会抛出错误...
有谁知道我在这里做错了什么。
检查以确保查询字符串不包含任何不 url 友好的字符,否则您需要 url 对其进行编码。为避免必须自己编码,您可以在构造 url
时使用 UriBuilder
class
var uriBuilder = new UriBuilder(uri);
uriBuilder.Query = ConcatParams(parameters);
Uri stationUri = uriBuilder.Uri;
//if NOT well formed
if(!stationUri.IsWellFormedOriginalString()) { //Note the `!` exclamation mark
//...code removed for brevity
} else {
//...code removed for brevity
}
它将url根据需要对任何值进行编码。
非常感谢您的帮助,我解决了它复制 cs 文件并在 modevelop 中创建一个空的 C# 项目并将旧文件放入新项目并重新加载引用,然后 new Uri(string) 工作...在我将项目创建为 gtk#2.0 之前,现在就像空的一样工作......我不知道原因......
我正在尝试做一个与 API REST 通信的桌面应用程序,然后我决定在我的 xubuntu 中使用 MonoDevelop 来做它。我尝试使用构造函数从字符串创建 Uri,但是当创建对象 Uri 时,它出现在我的 MonoDevelop 调试器中:
stationUri {System.Uri}
System.Uri AbsolutePath System.NullReferenceException: Object reference not set to an instance of an object AbsoluteUri System.NullReferenceException: Object reference not set to an instance of an object Authority System.NullReferenceException: Object reference not set to an instance of an object DnsSafeHost System.NullReferenceException: Object reference not set to an instance of an object Fragment System.NullReferenceException: Object reference not set to an instance of an object Host
System.NullReferenceException: Object reference not set to an instance of an object HostNameType System.NullReferenceException: Object reference not set to an instance of an object
urlConParametros https://api.thingspeak.com/channels/***/fields/4.json?api_key=***&results=2
字符串
由于安全原因,我没有显示完整的 URL.
以及与此错误相关的相应代码:
public string GetResponse_GET(string url, Dictionary<string, string> parameters)
{
try
{
//Concatenamos los parametros, OJO: antes del primero debe estar el caracter "?"
string parametrosConcatenados = ConcatParams(parameters);
string urlConParametros = url + "?" + parametrosConcatenados;
string responseFromServer = null;
Uri stationUri = new Uri(urlConParametros);
if(!stationUri.IsWellFormedOriginalString())
{
System.Console.WriteLine("Url Vacía");
}
else
{
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(stationUri);
wr.Method = "GET";
wr.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream newStream;
// Obtiene la respuesta
System.Net.WebResponse response = wr.GetResponse();
// Stream con el contenido recibido del servidor
newStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
// Leemos el contenido
responseFromServer = reader.ReadToEnd();
// Cerramos los streams
reader.Close();
newStream.Close();
response.Close();
}
return responseFromServer;
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == 404)
throw new Exception("Servicio Remoto No Encontrado: " + url);
else throw ex;
}
}
private string ConcatParams(Dictionary<string, string> parameters)
{
bool FirstParam = true;
string Parametros = null;
if (parameters != null)
{
Parametros = "";
foreach (KeyValuePair<string, string> param in parameters)
{
if(!FirstParam)
Parametros+="&";
Parametros+= param.Key + "=" + param.Value;
FirstParam = false;
}
}
return Parametros == null ? String.Empty : Parametros.ToString();
}
如果我运行完全代码,抛出下一个stackTrace关联(我删除了敏感数据):
Exception in Gtk# callback delegate Note: Applications can use GLib.ExceptionManager.UnhandledException to handle the exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object at System.Net.WebRequest.Create (System.Uri requestUri) [0x00000] in :0 at MainWindow.GetResponse_GET (System.String url, System.Collections.Generic.Dictionary`2 parameters) [0x0002b] in /home//MonoDevelop Projects///MainWindow.cs:92 at MainWindow.showAct (System.Object sender, System.EventArgs e) [0x0003f] in /home//MonoDevelop Projects///MainWindow.cs:34 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in :0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00053] in :0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0 at System.Delegate.DynamicInvokeImpl (System.Object[] args) [0x0010d] in :0 at System.MulticastDelegate.DynamicInvokeImpl (System.Object[] args) [0x0000b] in :0 at System.Delegate.DynamicInvoke (System.Object[] args) [0x00000] in :0 at GLib.Signal.ClosureInvokedCB (System.Object o, GLib.ClosureInvokedArgs args) [0x00067] in :0 at GLib.SignalClosure.Invoke (GLib.ClosureInvokedArgs args) [0x0000c] in :0 at GLib.SignalClosure.MarshalCallback (IntPtr raw_closure, IntPtr return_val, UInt32 n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data) [0x00086] in :0 at GLib.ExceptionManager.RaiseUnhandledException (System.Exception e, Boolean is_terminal) [0x00000] in :0 at GLib.SignalClosure.MarshalCallback (IntPtr raw_closure, IntPtr return_val, UInt32 n_param_vals, IntPtr param_values, IntPtr invocation_hint, IntPtr marshal_data) [0x00000] in :0 at Gtk.Application.gtk_main () [0x00000] in :0 at Gtk.Application.Run () [0x00000] in :0 at .MainClass.Main (System.String[] args) [0x00012] in /home//MonoDevelop Projects///Program.cs:13
我不知道为什么不能从字符串中正确建立 Uri... 然后如果我传递不正确的 Uri 来创建 WebRequest
也会抛出错误...
有谁知道我在这里做错了什么。
检查以确保查询字符串不包含任何不 url 友好的字符,否则您需要 url 对其进行编码。为避免必须自己编码,您可以在构造 url
时使用UriBuilder
class
var uriBuilder = new UriBuilder(uri);
uriBuilder.Query = ConcatParams(parameters);
Uri stationUri = uriBuilder.Uri;
//if NOT well formed
if(!stationUri.IsWellFormedOriginalString()) { //Note the `!` exclamation mark
//...code removed for brevity
} else {
//...code removed for brevity
}
它将url根据需要对任何值进行编码。
非常感谢您的帮助,我解决了它复制 cs 文件并在 modevelop 中创建一个空的 C# 项目并将旧文件放入新项目并重新加载引用,然后 new Uri(string) 工作...在我将项目创建为 gtk#2.0 之前,现在就像空的一样工作......我不知道原因......