First Request Fails With HTTP 400 (Bad Request) After Reading HttpRequest.InputStream

Oct 24, 2010

I develop an asmx web service (i.e. ASP.NET 2.0). There's a piece of code that may read the contents of the HTTP request (via HttpContext.Current.Request.InputStream) while processing it. I realise that InputStream may only be read once for a request, and I make sure I never try to read it more than once.

The problem seems to be that if InputStream happens to be read during the early stages of the application's lifecycle (e.g. after pskill w3wp, during Application_Start), the HTTP request fails with a HTTP 400 - Bad Request error, with no explanation given, no exception thrown and no entry in the httperr log. If it is read later (e.g. within the web method itself), requests run fine whether InputStream is read or not. Application_Start runs fine if InputStream isn't read.

Is this some sort of ASP.NET bug? IIS bug? Or am I doing something wrong by daring to read InputStream? And if so, is there another way to get a look at the "raw" contents of the request without disturbing the inner workings of IIS/ASP.NET? In short, adding this code within Application_Start is enough to reproduce this error: using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))reader.ReadToEnd();

View 1 Replies

Similar Messages:

WCF / ASMX :: Request Failed With HTTP Status 400: Bad Request Accessing Web Service

May 15, 2010

I have a webservice which works 100% fine on my developer machine. Where Web Service is installed on LOCALHOST on my developer machine,Then i went to my servers, I installed webservice on one server and map it with the server where the website is hosted, Then i tried accessing this service using BROWSER from my web server, it worked fine, That means the mapping was done perfect.Then i run my program on web server (website). It worked fine on page1, then on page2, but when i did the same and call same function on page3, It popped me any error of

View 4 Replies

Determine If A HTTP Request Is A Soap Request On HttpApplication.AuthenticateRequest

Jan 21, 2010

I there a way to know if a request is a soap request on AuthenticateRequest event for HttpApplication? Checking ServerVariables["HTTP_SOAPACTION"] seems to not be working all the time.

public void Init(HttpApplication context) {
context.AuthenticateRequest += new EventHandler(AuthenticateRequest);
protected void AuthenticateRequest(object sender, EventArgs e) {
app = sender as HttpApplication;
if (app.Request.ServerVariables["HTTP_SOAPACTION"] != null) {
// a few requests do not enter here, but my webservice class still executing
// ...
I have disabled HTTP POST and HTTP GET for webservices in my web.config file.
<remove name="HttpGet" />
<remove name="HttpPost" />
<add name="AnyHttpSoap" />
Looking at ContentType for soap+xml only partially solves my problem. For example,
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 1131
Content-Type: text/xml
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: ro
Host: localhost
mymethod: urn:[URL]

Some clients instead of having the standard header SOAPAction: [URL], have someting like in example above. "mymethod" represents the method in my web service class with [WebMethod] attribute on it and [URL] is the namespace of the webservice. Still the service works perfectly normal. The consumers use different frameworks (NuSOAP from PHP, .NET, Java, etc).

View 4 Replies

Writing Mp4 File From Request.InputStream?

May 28, 2010

I have a page posting data to me via HTTP POST. What i want is write posted data into mp4 video format file. Here my code how to write that file:

string strFilePath = "D:\Video.mp4";
using (FileStream fs = new FileStream(strFilePath, FileMode.Create))
byte[] bytes = new byte[Request.InputStream.Length];
Request.InputStream.Read(bytes, 0, (int)Request.InputStream.Length);
fs.Write(bytes, 0, bytes.Length);

My problem is that i got the file, but it's corrupt when playback. Is there any problem with my stream or i missing some decode for mp4 file?

View 2 Replies

C# - Change HttpContext.Request.InputStream

Apr 19, 2010

I am getting lot of errors for HttpRequestValidationException in my event log.

Is it possible to HTMLEncode all the inputs from override of ProcessRequest on web page. I have tried this but it gives context.Request.InputStream.CanWrite == false always.

Is there any way to HTMLEncode all the feilds when request is made?

public override void ProcessRequest(HttpContext context)
if (context.Request.InputStream.CanRead)
IEnumerator en = HttpContext.Current.Request.Form.GetEnumerator();
while (en.MoveNext())
//Response.Write(Server.HtmlEncode(en.Current + " = " +
long nLen = context.Request.InputStream.Length;
if (nLen > 0)
string strInputStream = string.Empty;
context.Request.InputStream.Position = 0;
byte[] bytes = new byte[nLen];
context.Request.InputStream.Read(bytes, 0, Convert.ToInt32(nLen));
strInputStream = Encoding.Default.GetString(bytes);
if (!string.IsNullOrEmpty(strInputStream))
List<string> stream = strInputStream.Split('&').ToList<string>();
Dictionary<int, string> data = new Dictionary<int, string>();
if (stream != null && stream.Count > 0)
int index = 0;
foreach (string str in stream)
if (str.Length > 3 && str.Substring(0, 3) == "txt")
string textBoxData = str;
string temp = Server.HtmlEncode(str);
//stream[index] = temp;
data.Add(index, temp);
if (data.Count > 0)
List<string> streamNew = stream;
foreach (KeyValuePair<int, string> kvp in data)
streamNew[kvp.Key] = kvp.Value;
string newStream = string.Join("", streamNew.ToArray());
byte[] bytesNew = Encoding.Default.GetBytes(newStream);
if (context.Request.InputStream.CanWrite)
context.Request.InputStream.Position = 0;
context.Request.InputStream.Write(bytesNew, 0, bytesNew.Length);

View 1 Replies

C# - Leaving A BinaryReader Object Un-disposed In Order To Keep Request.InputStream Alive?

Feb 1, 2011

I have a couple methods to handle the saving of an image using Request.InputStream. I have two extensions that share the HttpContext. In one of my methods, I'm using a BinaryReader to read in the contents and do the processing. However, naturally, when disposing the BinaryReader, it closes off the InputStream property on Request. My SECOND method uses the same input stream to create a thumbnail.

Bascially, I need a way to keep the Request.InputStream property alive after disposing the reader in the first method. Is this possible? Here are my two methods. SaveImageStream() is called first, then GenerateThumbnail().


View 2 Replies

Valum File Upload - Works In Chrome But Not IE - Image Img = Image.FromStream(Request.InputStream)

Dec 6, 2010

I'm using a slightly modified version of Valum's upload [github link], I've modified it to upload to a database but haven't modified the javascript that it is using to get the file into the Request as an InputStream. The following line of code is failing in IE 8 but is confirmed to work in Chrome. using (Image imgInput = Image.FromStream(Request.InputStream)) The error received is "Parameter not valid". It appears to be having an issue with the Input Stream being used but it exists/has data (not sure how to validate if the data is good or not).

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="file-uploader">
<p>Please enable JavaScript to use file uploader.</p>
<script src="/Scripts/fileuploader.js" type="text/javascript"></script>
<script type="text/javascript">
function createUploader() {
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/FileUpload/' + <%= Model.PropertyId %>,
debug: true
window.onload = createUploader;
public JsonResult FileUpload(int id)
byte[] newImageByteArray = GetByteArrayForResizedImage(350, Request.InputStream);
byte[] thumbnailByteArray = GetByteArrayForResizedImage(150, Request.InputStream);
//Add to DB
catch (Exception ex)
// This is where the exception is caught
return Json(new { success = false, message = ex.Message }, "application/json");
return Json(new { success = true }, "application/json");
private static byte[] GetByteArrayForResizedImage(int imageSize, Stream inputStream)
byte[] imageByteArray;
// For some reason in IE the inputStream here is causing it to crash
using (Image imgInput = Image.FromStream(inputStream))
//Image processing
return imageByteArray;
fileuploader.js - qq.FileUploader
* Class that creates upload widget with drag-and-drop and file list
* @inherits qq.FileUploaderBasic
qq.FileUploader = function(o){
// call parent constructor
qq.FileUploaderBasic.apply(this, arguments);
// additional options
qq.extend(this._options, {
element: null,
// if set, will be used instead of qq-upload-list in template
listElement: null,
template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
'<div class="qq-upload-button">Upload a file</div>' +
'<ul class="qq-upload-list"></ul>' +
// template for one item in file list
fileTemplate: '<li>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">Cancel</a>' +
'<span class="qq-upload-failed-text">Failed</span>' +
classes: {
// used to get elements from templates
button: 'qq-upload-button',
drop: 'qq-upload-drop-area',
dropActive: 'qq-upload-drop-area-active',
list: 'qq-upload-list',
file: 'qq-upload-file',
spinner: 'qq-upload-spinner',
size: 'qq-upload-size',
cancel: 'qq-upload-cancel',
// added to list item when upload completes
// used in css to hide progress spinner
success: 'qq-upload-success',
fail: 'qq-upload-fail'
// overwrite options with user supplied
qq.extend(this._options, o);
this._element = this._options.element;
this._element.innerHTML = this._options.template;
this._listElement = this._options.listElement || this._find(this._element, 'list');
this._classes = this._options.classes;
this._button = this._createUploadButton(this._find(this._element, 'button'));
fileuploader.js - qq.FileUploaderBasic
* Creates upload button, validates upload, but doesn't create file list or dd.
qq.FileUploaderBasic = function(o){
this._options = {
// set to true to see the server response
debug: false,
action: '/server/upload',
params: {},
button: null,
multiple: true,
maxConnections: 3,
// validation
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
// events
// return false to cancel submit
onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
// messages
messages: {
typeError: "{file} has invalid extension. Only {extensions} are allowed.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
showMessage: function(message){
qq.extend(this._options, o);
// number of files being uploaded
this._filesInProgress = 0;
this._handler = this._createUploadHandler();
if (this._options.button){
this._button = this._createUploadButton(this._options.button);

View 1 Replies

C# - How To Simulate Http Request Using WatiN With Specific HTTP Referrer And Query String

Dec 6, 2010

When I use WatiN to go to a specific web page, how can I fake the HTTP referrer with a query string (i.e. request is from google search with query string q=search_term)? So I can verify that the response header has the 301 redirect for specific referrer URL.

View 2 Replies

HttpHandlers / Modules :: Redirect A Page From Http To Https Using Http Module Begin Request Handler?

Jul 15, 2010

i redirect a page from http to https using http module begin request handler .i am calling webservice using ajax but it is saying webserice not defined .which otherwise works fineits work fine when rediect page in page_load instead .but i need to add function for https to http in every page. i still not know why ajax is not working when i use http module for redirect

View 3 Replies

WCF / ASMX :: Web Service Fails - 400 Bad Request - Only Certain Connections

Feb 21, 2011

I've got a web service on a server with valid IP and valid DNS entries. I'm using an asynchronous thread in a WPF .NET application to access methods from that web service. Under normal connection conditions, for almost all users, the connection and method works fine. Under a very specific condition - Verizon Aircard being used to connect, no VPN connection to the company through SSTP, on a PC with Forefront Client Security installed - the web service will return a "HTTP Error 400: Bad Request" error to the user. If the same user on the same PC connect their VPN connection, the method works flawlessly.

View 1 Replies

How To Hunt Down HTTP Request

Feb 25, 2010

It uses (webforms), bunch of jquery plugins and whatnot.

Problem: there's unnecessary HTTP request to localhost/undefined and that makes every request take ~1s longer than needed.

Question: is there any tactic to find guilty code?

Clue: undefined makes me think that there's JS involved.

Firebug log:

GET /undefined HTTP/1.1
Host: localhost:17817
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; lv; rv:1.9.2) Gecko/20100115
Accept: image/png,image/;q=0.8,/*;q=0.5
Accept-Language: lv,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-13,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost:17817/Default.aspx

if you right click a line in the code, it gives you a conditional breakpoint. Check the name of the variable that has the URL value, and set a condition when typeof URL === 'undefined' or url === 'undefined' and look at the stack

Just set breakproint at line 3400 (with no conditions). It does not go through there.

3397 ajax: function( s ) {
3398 // Extend the settings, but re-extend 's' so that it can be
3399 // checked again later (in the test suite, specifically)
3400 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

Narrowed issue down a bit => commented out 1 ascx controller that renders some images and uses gallerific jquery plugin and magic request dissapeared.

Problem was with galleriffic plugin initialization. It couldn't find anchor and it's href for creating thumbnails when there were no images or something. It's cool now...

View 3 Replies

C# - Http Request Issue In Asp.Net

Jul 24, 2010

I am using C# + VSTS 2008 + .Net 3.5 + ASP.Net + IIS 7.0 + ADO.Net + SQL Server 2008. I want to develop an ASP.Net aspx page which has the following function,

1 It could accept 3 Url parameters param1, param2 and param3, and the request looks like this,Âm2=defÂm3=ghi

2 When the page is responsed to client browser, I want to display a text input and a submit button nearby in the result html page, and value of text input is the same as param1, in this sample, abc will be displayed in text box, in the browser address bar, I want to keep the original long urlÂm2=defÂm3=ghi;

3 When the user change the value in text input, and click submit button, I want to send this request again to foo.aspx, and changing the param1 value to the value which user entered in text input, and at the same time, keep values of parame2 and param3 the same as last request's response. For example, when user requestsÂm2=defÂm3=ghi, and the page displays, when user changes text input from abc to google, the new request will beÂm2=defÂm3=ghi

Any reference samples? My question is I do not know how to implement so many functions in one aspx page.

View 1 Replies

Generating HTTP Request?

Aug 21, 2010

In how many ways can an HTTP request be generated?

View 2 Replies

Get MAC Address From HTTP Request

Jul 22, 2010

picking up the Users MAC address from the HTTP request.

The users will be from OUTSIDE my network.

View 3 Replies

WCF / ASMX :: Uploading File To Webservice Method Fails - Request Format Is Invalid?

Apr 27, 2010

have a working ASP.NET 3.5 webservice that accepts standard POST requests using an encoding type of application/x-www-form-urlencoded. I then added a method which needs to accept an uploaded file. We change the encoding type of the request to multipart/form-data so that we can get the file data and now we receive the following error:System.InvalidOperationException: Request format is invalid: multipart/form-data

View 3 Replies

HTTP Response And Request In Binary

Feb 21, 2010

I need to I can make the web request to a webservice which take a XML argument. And is expected to return a Binary response. I am able to make the request but while recieving the response back I am unable to get the response in binary. When I read the response
using streamreader see the header and some attached "HEBRISH" words probably binary but unable to sepreate it out. Please help in seprating out the binary the response data.

View 1 Replies

MVC :: Handle Dates In Mvc When Request Is A Http GET?

May 10, 2010

how do u handle dates in mvc when request is a http GET? I remember some discussoin on this last year but cant find the posts.. things like culture unaware, splitting the date field to 3 text fields insted of 1.

View 6 Replies

How To Edit HTTP Request With Fiddler

Aug 5, 2010

Is it possible to edit HTTP request using fiddler so that my application hosted elsewhere return true for the following code block

HttpContext.Current.Request.Url.Host == "localhost"

View 1 Replies

Why Parameters Are Encoded When Sent Through HTTP Request

Feb 17, 2011

I am curious to know the reasons why the HTTP request encodes(URLEncoded) all the parameters before sending it across the network in POST request.

View 1 Replies

Making Http Request From Code Behind

Mar 3, 2011

I am trying to implement Message API

I am not sure how I will be calling this from code-behind and in their snippet it says:


View 2 Replies

MVC :: IIS Responding With 404 On HTTP HEAD Request?

Jul 28, 2010

I'm currently trying to setup testing with Selenium. It seems that Selenium sends a HEAD request to my route /Home/Index before it sends the GET request. This causes all my tests to fail. I was wondering how I would go about getting HEAD requests to respond correctly (not 404).

View 3 Replies

Load Images With Http Request?

Nov 15, 2010

i have a usercontrol which displays 1 inage this control is used several times on my page. the problem i have some images can be large so i need to load them using http request i think, i want to display a loading image until the actual image is loaded, what would be the best way to do this?

View 2 Replies

WebService Remote Invoking Fails / Request Format Is Unrecognized For URL Unexpectedly Ending In '/List'

Jan 11, 2011

I have a web service hosted on a web server, I invoke the web service using jquery ajax.

The service returns results successfully when invoked locally from the server, but it fails when invoked from a remote client machine (not in the same domain).

I see the request fail in the firebug returning error (401 UnAuthorized) and the response has the following error (Request format is unrecognized for URL unexpectedly ending in '/List').

View 3 Replies

Reading InputStream Into Byte Array

May 21, 2010


My fu.PostedFile shows data in it. Each index of the array has different value in it. But arrFileByte shows all the index have 0 as their value. I've used this very code to upload files in the database before. What might be the resaon it is not working now.

View 6 Replies

Read A HTTP Post Request With Some Data

Nov 9, 2010

I am using an Zencoder API to transcode video files. Once the job is completed they will do a HTTP POST with XML or JSON data containing the Job ID and other info to the url we provide.

So if URL is or .ashx, how can I read the data they post?

excuse me for the underlines, i thought that would make my query stand out.

View 6 Replies

Copyrights 2005-15, All rights reserved