Tag: httpresponse

C#Web API基于GET请求的XML或JSON

我的config.Routes设置为: config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{id}”, defaults: new { id = RouteParameter.Optional } ); 有了这个,我可以使用: localhost:port/api/products – 获取完整的产品列表 localhost:port/api/products/# – 获取具有给定id的单个产品 基于浏览器,我得到了不同的格式(默认情况下,FireFox和Google Chrome中的XML格式以及Internet Explorer中的JSON格式)。 我主要需要JSON,所以最初我添加了: var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); 所以我的回答总是在JSON中。 在这一点上,一切都是有意义的,我在上面提到的两个GET请求上获得了JSON格式的响应。 然后我偶然发现了这个stackoverflowpost 。 认为根据GET请求为您自己选择要返回的格式是一个很好的function。 但是,当我替换上面提到的config.Routes和JSON-only代码时: config.Routes.MapHttpRoute( name: “API UriPathExtentsion”, routeTemplate: “api/{controller}.{ext}/{id}”, defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional } […]

ASP.NET JavaScriptSerializer需要HttpResponse吗?

似乎System.Web.Script.Serialization.JavascriptSerializer类尝试获取当前请求的HttpResponse,可能是为了应用适当的字符编码。 但是,这意味着当您要在范围内使用没有HttpContext的类时,它会出现以下exception+堆栈跟踪: [HttpException (0x80004005): Response is not available in this context.] System.Web.HttpContext.get_Response() +8753496 System.Web.Util.HttpEncoder.get_Current() +39 System.Web.HttpUtility.JavaScriptStringEncode(String value, Boolean addDoubleQuotes) +13 System.Web.Script.Serialization.JavaScriptSerializer.SerializeString(String input, StringBuilder sb) +31 System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +240 System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355 System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, […]

如何将大量数据传递到我的Web API应用程序?

我在Web API控制器中有这个代码: [Route(“{unit}/{begindate}/{enddate}”)] [HttpPost] public void Post(string unit, string begindate, string enddate, [FromBody] string stringifiedjsondata) { List _produceUsageList = JsonConvert.DeserializeObject<List>(stringifiedjsondata); string _unit = unit; string _begindate = String.Format(“{0}01”, HyphenizeYYYYMM(begindate)); string _enddate = GetEndOfMonthFor(enddate); string appDataFolder = HttpContext.Current.Server.MapPath(“~/App_Data/”); string htmlStr = ConvertProduceUsageListToHtml(_produceUsageList); string htmlFilename = string.Format(“produceUsage_{0}_{1}_{2}.html”, _unit, _begindate, _enddate); string fullPath = Path.Combine(appDataFolder, htmlFilename); File.WriteAllText(fullPath, htmlStr); […]

如何将原始HTTP响应解析为HttpListenerResponse?

如果我将原始HTTP响应作为字符串: HTTP / 1.1 200好的 日期:2010年5月11日星期二07:28:30 GMT 过期:-1 Cache-Control:private,max-age = 0 Content-Type:text / html; 字符集= UTF-8 服务器:gws X-XSS-Protection:1; 模式=块 连接:关闭 … 有没有一种简单的方法可以将它解析为HttpListenerResponse对象? 或者至少是某种.NET对象,所以我不必使用原始响应。 我目前正在做的是提取标题键/值对并在HttpListenerResponse上设置它们。 但是有些头文件无法设置,然后我必须剪切响应的主体并将其写入OutputStream。 但身体可以被gzipped,或者它可能是一个图像,我还无法工作。 并且一些响应在任何地方都包含随机字符,这看起来像编码问题。 这很麻烦。 我正在获得原始响应,因为我正在使用SOCKS发送HTTP请求。 我正在处理的程序基本上是一个HTTP代理,它可以通过SOCKS代理路由请求,就像Privoxy那样。

如何为来自BITS(后台智能传输服务)的Range请求设置正确的HTTP Response对象?

我需要实现一个可以向位发送文件的Web服务(后台智能传输服务)。 语言是ASP.NET(C#)。 我遇到的问题是“范围”的东西。 我的代码当前收到http请求(有效范围出现在0 – 4907的http标头中),随后在响应对象中输出一部分字节数组。 这是我的服务器代码: _context.Response.Clear(); _context.Response.AddHeader(“Content-Range”, “bytes ” + lower.ToString() + “-” + upper.ToString() + “//” + view.Content.Length.ToString()); _context.Response.AddHeader(“Content-Length”, upper.ToString()); _context.Response.AddHeader(“Accept-Ranges”, “bytes”); _context.Response.ContentType = “application/octet-stream”; _context.Response.BinaryWrite(data); _context.Response.End(); 接下来发生的事情是后续请求根本没有标题中的任何“范围”键……就像它要求整个文件一样! 不用说,位作业错误表明服务器响应无效。 我怀疑这一切都归结为服务器在响应对象中返回的标题…我很确定我在这里遵循协议。 如果有人可以帮忙解决这个问题,我将不胜感激……意思是……我会一直在寻找! 问候

如何将Content-Length,Content-Type和Last-Modified添加到HTTP响应消息头

如何使用.net将Content-Length,Content-Type和Last-Modified添加到HttpResponseMessage标头。 我需要在添加这些字段后手动将所有这些值附加到响应中,我需要从服务器返回响应。 我试图以这种方式添加这些字段 httpResponse.Content.Headers.Add(“Content-Length”, item.Size.ToString()); httpResponse.Content.Headers.Add(“Content-Type”, item.ContentType); 但它抛出exception为 “你调用的对象是空的”。 如果我这样添加 httpResponse.Headers.Add(“Content-Length”, item.Size.ToString()); httpResponse.Headers.Add(“Content-Type”, item.ContentType); 我得到了一个错误的错误 “Misused header name。确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用。” 请任何人帮我将这些字段添加到HttpResponsesMessage中。

为什么为未使用的变量赋值会对此异步代码的function产生影响?

我有这个代码: private async Task SavePlatypusComplianceFileOnServer(string year, string month) { string monthAsMM = ReportRunnerConstsAndUtils.GetMonthAsMM(month); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(ReportRunnerConstsAndUtils.SERVER_BASE_ADDRESS); String uriToCall = String.Format(“/api/PlatypusCompliance/{0}/{1}{2}”, _unit, year, monthAsMM); HttpResponseMessage response = await client.PostAsync(uriToCall, null); } ……工作正常 不过,看着它,我心里想,“自我,为什么你在不使用它时为”响应“赋值?为什么不在没有它的情况下调用方法?毕竟,Visual Studio或Resharper灰色用“回应”表示你没有实际意义/冗余。“ 所以我将代码更改为: private async Task SavePlatypusComplianceFileOnServer(string year, string month) { . . . // all but the […]

如何从Pacer.gov API提出案例请求?

我正在尝试向名为Pacer.gov的API发出请求。 我期待一个文件被退回,但我没有得到它。 有人可以帮我解决我所缺少的问题吗? 所以我的C#Rest调用如下所示: (变量PacerSession是我得到的身份validationcookie(在@ jonathon-reinhart的帮助下);在这里阅读更多相关内容: 如何使用RestSharp将登录名和密码POST到API? ) var client = new RestClient(“https://pcl.uscourts.gov/dquery”); client.CookieContainer = new System.Net.CookieContainer(); //var request = new RestRequest(“/dquery”, Method.POST); var request = new RestRequest(Method.POST); request.AddParameter(“download”, “1”); request.AddParameter(“dl_fmt”, “xml”); request.AddParameter(“party”, “Moncrief”); request.AddHeader(“user-agent”, “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36”); request.AddHeader(“content-type”, “text/plain; charset=utf-8”); request.AddHeader(“accept”, “*/*”); request.AddHeader(“accept-encoding”, “gzip, deflate, sdch”); […]

使用WebAPI HttpResponseMessage时下载文件提示

我的API中有一个返回HttpResponseMessage的方法: [HttpGet, HoodPeekAuthFilter] public HttpResponseMessage GlobalOverview() { try { StatsRepo _statsRepo = new StatsRepo(); string file = _statsRepo.IncidentData().AsCSVString(); if (file == null) { return Request.CreateResponse(HttpStatusCode.NoContent); } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StringContent(file); result.Content.Headers.ContentType = new MediaTypeHeaderValue(“application/octet-stream”); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(“attachment”); result.Content.Headers.ContentDisposition.FileName = “GlobalOverview.csv”; return result; } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError); […]

HttpContext.Current.Response.AddHeader()未设置Content-Type标头

我正在使用第三方软件从html文档中呈现PDF。 我创建了一个小测试项目并使用的OnClick事件,我能够从目录中读取一个html文档并将其呈现为PDF而没有任何问题。 响应创建如下: HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader(“Content-Type”, “application/pdf”); HttpContext.Current.Response.AddHeader(“Content-Disposition”, String.Format(“{0}; filename=Test.pdf;”, “inline” )); HttpContext.Current.Response.BinaryWrite(pdfBuffer); HttpContext.Current.ApplicationInstance.CompleteRequest(); 当我查看Chrome中的响应时,我可以看到正确设置了Content-Type: 内容处置:内联; 文件名= HtmlToPdf.pdf; 内容长度:101482 内容类型:应用程序/ PDF 我试图将上述内容转移到我当前的项目中。 唯一的区别是,而不是一个我在DevExpress网格视图中使用自定义按钮。 我最初在回调面板中处理了自定义按钮单击,但未设置Content-Type。 在Chrome中查看响应certificate了这一点: 内容处置:内联; 文件名= 5.pdf; 内容编码:gzip 内容长度:149015 内容类型:text / plain的; 字符集= utf-8的 我也尝试过使用gvDocuments.CustomButtonCallback += new ASPxGridViewCustomButtonCallbackEventHandler(gvDocuments_CustomButtonCallback); 事件但仍未设置Content-Type。 任何人都有任何想法,为什么我不能在上述场景中设置Content-Type?