2014-09-25 69 views
-1

我了解我发布了一个非常广泛的域的问题,但是我找不到解决这种常见问题的方法。我的问题特定于Visual Studio 2013,我对微软开发环境来说真的很陌生。在Visual Studio 2013中进行REST API调用

我想用JSON响应做一个简单的休息API调用。这也是迄今为止它给我已经写了代码System.Security.SecurityException

private void btnAlert_Click(object sender, RoutedEventArgs e) 
    { 
     Console.Write("Event Fired"); 
     MessageBox.Show("Event Fired"); 
     String url = "http://www.traderscockpit.com/ModulusController?action=getInstruments"; 

     HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 
     request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request); 
     try 
     { 
      WebClient client = new WebClient(); 
      client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_downloaded); 
      client.DownloadStringAsync(new Uri(url)); 
     }catch(Exception e1){ 
      Console.Write(e1.ToString()); 
      MessageBox.Show("Error Event Fired"); 
     } 
    } 

    private void wc_downloaded(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (!e.Cancelled && e.Error == null) 
     { 
      string textString = (string)e.Result; 
      Console.Write(textString); 
      MessageBox.Show(textString); 
     } 
     else if(e.Cancelled){ 
      Console.Write("canceled"); 
      MessageBox.Show("cancelled"); 
     } 
     else if (e.Error!=null) 
     { 
      Console.Write(e.Error.ToString()); 
      MessageBox.Show(e.Error.ToString()); 
     } 
    } 
从这个

除此之外,一些代码暗示此功能,VS 2013是不支持:

 HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 
     Response res=request.GetResponse(); 

有些人使用System.Net.Http;和System.Net.Http.Headers;命名空间,这再次不是在我的vs 2013年。

我真的很新,真的很震撼。提前致谢。

+0

你所说的“是给'System.Security.Security'”意思?请注意,您正在使用的Visual Studio版本在执行时确实不会受到太多影响。知道你的目标是哪个版本的.NET以及哪个项目类型更重要。特别是,'System.Net.Http' * *是可用的,如果你有正确的程序集引用... – 2014-09-25 18:00:00

+0

对不起System.Security.SecurityException。纠正它。 – Sourabh 2014-09-25 18:00:52

+0

“不支持”你会得到错误吗?我建议你避免使用'HttpWebRequest'并使用'HttpClient'来代替。例如'Install-Package Microsoft.Net.Http' – 2014-09-25 18:01:22

回答

0

使用Silverlight应用程序,您需要向与您的Silverlight应用程序不在同一个域中的任何URI请求权限。这可以通过clientaccesspolicy.xml文件完成。例如:

<?xml version="1.0" encoding="utf-8"?> 
<access-policy> 
    <cross-domain-access> 
    <policy> 
     <allow-from http-request-headers="*"> 
     <domain uri="http://contoso.com"/> 
     </allow-from> 
     <grant-to> 
     <resource path="/" include-subpaths="true"/> 
     </grant-to> 
    </policy> 
    </cross-domain-access> 
</access-policy> 

欲了解更多信息,请参阅http://blogs.msdn.com/b/cesardelatorre/archive/2008/09/29/using-silverlight-2-0-clientaccesspolicy-xml-vs-crossdomain-xml-for-web-service-cross-domain-access.aspx

相关问题