In web.config, the error page is set to /errorpages/error.aspx
<httpErrors errorMode="Custom" existingResponse="Replace" >
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="/errorpages/error.aspx" responseMode="ExecuteURL" />
</httpErrors>
But when the page /errorpages/error.aspx is loaded in the browser, the status code is 200. This results in various problems, like the fact that when I have a JS file that's in the wrong URL, instead of getting a specific error, I get a JS error like unexpected < (same logic is used for 404.aspx page).
So, to fix this, inside error.aspx, in Page_Load(), I set
Response.StatusCode = 500;
and the page is returned with 500 status code, which can be observed in the browser.
The problem is that if I place a breakpoint inside Page_Load() in /errorpages/error.aspx, it is being hit twice. First time it enters the StatusCode is 200, it sets it to 500, so my suspicion is that IIS tries to handle that from web.config, it loads the page again. And again the StatusCode is 200, and changes to 500, but this time it doesn't trigger another execution.
This is probably caused by the fact that the exceptions are being handled in Global.asax.cs, where after handling, this is executed:
Server.TransferRequest("/errorpages/error.aspx?someExceptionInfo=" + exceptionInfo);
So this diagram shows what I think is happening:
I could just set a status code instead of calling TransferRequest, and let IIS handle it, and pass the exception info via the Session. But I'm worried that at some point it might cause some kind of redirect loop or something on Production servers.
Question (one of them):
How do I ensure I won't get a redirect loop?
How do I configure IIS to make error pages return a status code without actually writing Response.StatusCode = ***?
How do I impede my application from repeating execution of the page when I set the StatusCode?
Related
I am facing a weird issue, I am running Quartz jobs to fetch data from 2 different URL, but getting timeout error on one, another is working just fine. The inner exception of error that I get says 'The operation has timed out'.
One more interesting thing is that I am not getting this error on my local system, on my local, both the jobs are fetching data correctly, but on server one fails.
I also spoke to the team of the website from which I am fetching data, they told me that their configuration for both urls are same, so there is no issue at their end.
I have made some changes in my webconfig file while trying to fix this issue by reading online, but no luck yet.
I have added this line in the appSettings tag in web.config
<add key="SqlCommandTimeOut" value="10000000" />
My connection string looks like:
<add name="xyzDBEntities" connectionString="metadata=res://*/xyzDB.csdl|res://*/xyzDBEntities.ssdl|res://*/xyzDBEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL1234.xyzsite.com;initial catalog=xyzDB;User Id=xyzDB_admin;Password=xyzpassword;App=EntityFramework"" providerName="System.Data.EntityClient" />
It would be great if someone can help me in sorting this out. Please let me know if more details are needed. Thanks!
Extending WebClient class and overriding GetWebRequest() by setting timeout to 1 minute resolved my issue.
public class CustomWebClient : WebClient{
protected override WebRequest GetWebRequest(Uri address){
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.Timeout = 60000; //1 minute timeout
return request;
}
}
I've got a text area that contains HTML. I expect the content to be escaped when posted to the controller method but I'm finding it is escaped twice. What could possibly cause this? See the example below:
Pulled from request:
<b>test</b>
WebUtility.HtmlDecode 1st time:
<b>test</b>
WebUtility.HtmlDecode 2nd time:
<b>test</b>
I'm no expert when it comes to web development but I've got about 2 years of experience. This is the first time I've seen anything like this. I've attempted adding the following sections to my Web.config with no luck:
<pages validateRequest="false" />
<httpRuntime requestValidationMode="2.0" /
<security>
<requestFiltering allowDoubleEscaping="false" />
</security>
Please let me know if I can provide more information.
It turns out the problem lay in the textarea itself. In the view it was just a standard textarea, but in Javascript document.Ready was then made to be a kendoEditor. The kendoEditor was encoding the HTML first, then ASP.net was applying its standard encoding as well. Setting the attribute encoded equal to false fixed the issue:
$("#editor").kendoEditor({
encoded: false
});
Update:
I found later that setting the encoded attribute to false would introduce another problem. On submit I received a "A potentially dangerous Request.Form value was detected from the client" error when using formatting tools from the built-in KendoEditor toolbar. My solution was to double-decode the posted request:
WebUtility.HtmlDecode(WebUtility.HtmlDecode(Request["value"]));
Already looked at this:
Sys.WebForms.PageRequestManagerParserErrorException - what it is and how to avoid it
Problem is that it's only happening on my dev box. Two other developers are fine.
It's consistent and reproducible - I've tried deleting temporary internet files, deleted my obj and bin files and rebooting.
The response is clearly truncated when I look at it in the debugger when it hits the error.
Where else do I need to check to clear/clean out?
The error I'm seeing in the code is:
Microsoft JScript runtime error:
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed. Common causes for this
error are when the response is modified by calls to Response.Write(),
response filters, HttpModules, or server trace is enabled. Details:
Error parsing near ' </tr>
'.
_endPostBack: function PageRequestManager$_endPostBack(error, executor, data) {
if (this._request === executor.get_webRequest()) {
this._processingRequest = false;
this._additionalInput = null;
this._request = null;
}
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
Sys.Observer.raiseEvent(this, "endRequest", eventArgs);
if (error && !eventArgs.get_errorHandled()) {
throw error; // THIS IS WHERE THE ERROR IS THROWN
}
},
This is during an Ajax postback.
There are no Response.Write calls.
I'm using Cassini/VS 2010 Development Server, how do I tell if there are filters?
ditto
Server trace is not enabled
No calls to Server.Transfer
In firebug, I can see that the response to the POST is truncated. Problem happens in Firefox or IE, and whether I'm debugging in VS or not.
The problem does go away if I switch to IIS Express in Visual Studio, and then it returns when I am back on the ASP.NET Development Server.
I have seen this problem before with Cassini. I solved it by adding the following to the Web.config:
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
The entry above is for version 1.0. Make sure that the Version and PublickKeyToken attributes match the ASP.net Ajax version that you are using. Also you may want to disable event validation in your page:
enableEventValidation="false"
Hope it helps!
After our talk, my idea was that maybe for some reason the cassini can not hold a big post back field, and a big one is the viewstate.
So if the viewstate is a very big one maybe this is the problem.
A second case maybe if the viewstate contain characters that some time not pass by the router or some firewall and cut them as possible attach or virus.
Possible solutions: To compress the viewstate, and/or to cut it in smaller parts.
You can also download the latest developer edition version of Cassini with lot of improvements at http://cassinidev.codeplex.com/ that maybe have fix this issue.
Are you using some kind of http module compression? It seems to cause problems very much like yours when using updatepanels. Please review this post.
If you are not ussing compression, maybe another httpmodule related error is making you suffer. Try adding this to your webpage:
enableEventValidation="false"
Maybe you could catch the exception with this kind of code:
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message+e.Exception.StackTrace ;
}
<asp:ScriptManager ID="ScriptManager1" runat="server"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">
</asp:ScriptManager>
Source for that last thing.
Error:
Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500
solution:
<add key="aspnet:MaxHttpCollectionKeys" value="100000"/ >
Add above key in app setting section.
I have a Silverlight 3 application, which 95% of the time is successfully requesting data from a WCF Service (in the same webapp) and displaying it.
This happens infrequently, usually if I hit the service a bunch of times quickly, but sometimes it'll happen on a single lone request.
Every once in a while, if I request a lot of transactions in a short period, I get one of two exceptions, they both occure in the Reference.cs file in the EndMyMethod(System.IAsyncResult result).
There are a few methods, and the exceptions occure on any number of them. The first one, is a TimeoutException() which I understand and it makes sense, the second one, which I totally don't get is the "CommunicationException() was unhandled by user code: The remote server returned an error: NotFound."
I've put try..catch blocks both arround the .MyMethodAsync() and in the handler for MyMethodCompleted both to no avail, as the exception occurs in the generated Reference.cs file.
Any help is greatly appreciated.
update
Reference.cs -- generated by "Add Service Reference"
public System.IAsyncResult BeginTogglePicked(string ID, string toggle, System.AsyncCallback callback, object asyncState)
{
object[] _args = new object[2];
_args[0] = ID;
_args[1] = toggle;
System.IAsyncResult _result = base.BeginInvoke("TogglePicked", _args, callback, asyncState);
return _result;
}
public void EndTogglePicked(System.IAsyncResult result)
{
object[] _args = new object[0];
// This is the line where the Exception is Thrown
base.EndInvoke("TogglePicked", _args, result);
}
Calling Code -- pickedIDs is a list of Strings, and userIDSelecting is a string defined at the top of the procedure. The Event Handler mdc_TogglePIckedCompleted is empty at the moment.
MapDataClient mdc = new MyDataClient();
mdc.TogglePickedCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(mdc_TogglePickedCompleted);
foreach (string id in pickedIDs)
{
mdc.TogglePickedAsync(id, userIDSelecting, mdc);
}
Update 2
This is the "InnerException" from the CommunicationException: System.Net.WebException: The remote server returned an error: NotFound.
Not sure if this is any more helpful, since it doesn't give any extra details. As I said, this happens intermitently not every time I call a service method. I'd also like to point out that the same call will work sometimes and not others, I'm starting to think this issue is because IIS is failing to respond to my service calls, thoughts?
Update 3
When I mean intermiently, I mean truel intrmitent. This may only occur a single time in a user's session, and it may only occur on one of fifty sessions. Its not an all-or-nothing sitation. The calling application is hosted within the same "webite" as the WCF Service, so I don't think a clintaccesspolicy.xml is the issue, but I could be wrong.
The message that you are getting are probably a red herring :-(
When internal WCF service exceptions are thrown, these will ALWAYS manifest themselves as Server Not Found exceptions in the Silverlight UI. This is because the HTTP response is of type 500. The best article I read on this was from David Betz - http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2 (this was written for SL2, but the concepts still holds for SL3. Also, some of his approaches are for purists - e.g. "NEVER" using the Add Service Reference features from VS - you don't have to follow all his advice ;-) )
Anyway, back to your question, you need to convert the response type to 200 and parse the exception in the message. This can be done using a MessageInspector (in the service and SL app).
There are quite a few articles on how
to do this on the net:
http://www.liquidjelly.co.uk/supersearch/?q=silverlight%20messageinspector&lang=en-GB.
A working example can be downloaded
from CodePlex:
http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660
(download link at the bottom of the
page "Message Inspectors")
Some of these approaches can seem quite daunting - take some time to understand this - the concept is crucial for WCF <--> SL applications, and it makes sense once you get it :-)
We've used this with a lot of success since the start of the year, so if you need anymore help with this just let me know.
Can I recommend always, always having Fiddler running when you are working with Silverlight and WCF?
Is your service returning exception details to the client? By default it does not. You could add the following attribute to your service class.
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class MyService ...
You may find you're getting some kind of server-side exception that is not visible to the client.
Make sure you have a clientaccesspolicy.xml file. Otherwise you may get that error cause the policy file cannot be found.
I had exactly the same problem as you - absolute nightmare, it would work sometimes and then just stop.
After reading your post earlier I kept looking for clientaccesspolicy info and found this (can't remember where), but I use it and it now works fine!
Hope the same is good for you :) My file was missing the extra detail on the allow-from section.
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" />
</allow-from>
<grant-to>
<resource include-subpaths="true" path="/"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.
Response.StatusCode = 401;
Response.End();
Set Response.StatusCode and then - if you need to stop execution - call Response.End().
I think I still prefer:
throw new HttpException(401, "Auth Failed")
I don't think the Response.StatusCode method triggers custom errors defined in the web.config file, e.g.
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
<error statusCode="401" redirect="AuthFailed.htm" />
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
Throwing a new exception definitely triggers custom errors.
Also, you might be using an application-wide error logging facility, like ELMAH or something, and I don't think the Response.StatusCode method would be logged there, either.
Note: I see now the question said that, ideally, the standard IIS error page should be shown. Obviously, the custom error pages are not wanted. I would use the Response.StatusCode method in that case.
You should be able to just use the following, according to MSDN.
Throw New HttpException(401, "Auth Failed")
Edit After seeing the other responses setting the status code would be more appropriate.
One additional comment.
If a portion of the page has already been written to the output buffer then it is important that you clear any buffered content or the page may not appear correctly.
This is quite likely in a templated environment. e.g. Master pages...
Response.ClearContent();
Response.StatusCode = 401;
Response.End();