使用System.Web.Http的引用不起作用? (使用.net 4.5)

时间:2015-12-08 20:55:37

标签: c#

在这里搜索了两个多小时之后,我仍然无法得到我在这里拼凑起来的代码,因为我相信缺少参考资料。

我得到的错误来自下面的部分,其中当前上下文中不存在请求。

return Request.CreateResponse(HttpStatusCode.BadRequest);

我得到的另一个错误是getFileFromID在当前上下文中也不存在。

getFileFromID(id, out fileName, out fileSize);

我确信这只是一个我想念的简单参考,但我已经尝试使用谷歌搜索,但仍无法找到解决方案。有谁知道为什么我一直得到“当前上下文中不存在”的错误?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Morningstar.JSON;
using Ionic.Zip;
using System.Net;
using System.IO.Compression;
using System.Windows.Forms;
using Ionic.Zip;
using System.Web;
using System.Net.Http;
using System.Web.Http;


namespace MS_Hourly_API_Call
{
class Program
{

 public static void Main(string[] args)
    {
        // THIS ONE IS DIFFERENT FROM THE ORIGINAL DOWNLOADCURVEDATA
        string feedName = "RiskReporting_Power_Hub_Hourly";
        var url = String.Format("https://mp.morningstarcommodity.com/lds/lists/{0}/content?fromDateTime={1}", feedName, DateTime.Today.ToString("yyyy-MM-dd")); 
        string username = "asdfk"; //removed username
        string password = "asdfasdf"; //removed password

        // Setup web connection with appropriate authentication parameters and requesting a JSON response
        using (var syncClient = new WebClient())
        {


            syncClient.Headers.Add("Accept", "application/json");
            syncClient.Credentials = new NetworkCredential(username, password);

            // Retrieve and parse the JSON response
            var jsonContent = syncClient.DownloadString(url);
            var feedItems = JsonConvert.DeserializeObject<List<FeedContent>>(jsonContent);

            // Download each item
            syncClient.Headers.Remove("Accept");




        }
    }
 public HttpResponseMessage GetFile(string id)
 {
     if (String.IsNullOrEmpty(id))

         return Request.CreateResponse(HttpStatusCode.BadRequest);

     string fileName;
     string localFilePath;
     int fileSize;

     localFilePath = getFileFromID(id, out fileName, out fileSize);

     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
     response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
     response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
     response.Content.Headers.ContentDisposition.FileName = fileName;

     return response;
 }
}

}

2 个答案:

答案 0 :(得分:2)

据我所知,没有IIS没有Request对象,你的代码显然不能在IIS服务器上运行

答案 1 :(得分:1)

如果这是一个调用Web来获取文件的应用程序,那么您可以使用WebClient获取文件https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx

它内置了同步或异步下载文件的方法