2017-06-10 29 views
0

我试图做一个与API REST通信的桌面应用程序,然后我决定用我的xubuntu中的MonoDevelop来完成它。我试图从字符串构造函数,但是,当创建对象乌里创建一个开放的,它出现在我的MonoDevelop调试器:在C#中创建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(); 
} 

,引发相关联的下一栈跟踪(I除去敏感数据):

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

我不t知道为什么不能正确地建立Uri从字符串...然后,如果我通过不正确的Uri创建WebRequest也会引发错误...

是否有任何我知道我在这里做错了什么。

+0

向我们展示urlConParametros的前10个字符。 – mjwills

+0

我编辑过,现在显示前10个字符 –

+0

@NikashaVoncarstein查询字符串中的值可能需要进行网址编码。但是由于你没有展示一个值的例子,这只是一个猜测。 – Nkosi

回答

0

非常感谢你的帮助,我解决了它复制cs文件和在monodevelop中创建一个空白的C#文件,并将旧文件放入新项目并重新加载引用,然后新的Uri(字符串)工作...之前我创建了gtk#2.0项目,现在像空白和作品...我知道原因...

0

检查以确保查询字符串不包含任何不受网址友好的字符,否则您需要对其进行网址编码。为了避免contructing网址时

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编码的任何值,以自己编码它,你可以使用UriBuilder类。

+0

嗨!感谢您的帮助。我改变了之前的代码行: // urlGET =“https://api.thingspeak.com/channels/__/fields/4.json” \t \t \t Uri uri = new Uri(urlGET); \t \t \t var uriBuilder = new UriBuilder(uri); \t \t \t uriBuilder.Query = ConcatParams(parameters); \t \t \t Uri stationUri = uriBuilder。URI; (stationUri.IsWellFormedOriginalString()) 但在行var uriBuilder = new UriBuilder(uri);在uri和uriBuilder中都出现错误:“对象引用未设置为对象的实例” –