Handling exceptions before startup - asp.net-core

I have an application that can throw an InvalidOperationException during the startup process before the host has been created. What I would like to do is capture this error, and handle it by displaying a static, custom error page (i.e. ErrorPage.html)
Is this possible? Everywhere I seem to look makes it seem as though this is an impossible task and that the default 500.30 - ASP.NET Core app failed to start is the only page that will appear in a situation where the host fails to establish by the time the exception is thrown.

One option to achieve a custom error page on host errors generating 500 responses would be to use some gateway or proxy in front of your app. The idea would be to handle certain responses by showing some error content from the gateway.
Options would include custom error pages in Azure Application Gateway or a middleware handler if using a YARP proxy instance.

For IIS use web.config and add a section inside element <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<error statusCode="500" subStatusCode="30" path="ErrorPage.html" responseMode="File" />
</httpErrors>
Check docs for more information

Related

Possible proxy issue with WSO2 API Manager

Whenever I try to add the following endpoint, "http://ws.cdyne.com/phoneverify/phoneverify.asmx", during the Managed API setup process and press the Test button I get an error on the server. ERROR - APIProviderHostObject Error occurred while connecting to backend : "stackOverflow preventing me from showing this link", reason: Connect to ws.cdyne.com:80 timed out
When I try this exact same process on a machine outside of our proxy it works fine. I have gone into the axis2.xml file and added proxy information and even went as far as installing cntlm and setting the proxy to localhost - same error.
I can browse to the above link just fine on this machine.
My environment is Windows 10.
I assume you talk about clicking the Test button when providing Backend Endpoint in API publisher.
The way that Test button works at the moment (as far as I understand) is that it invokes HTTP HEAD method on the endpoint provided (because according to RFC 2616, "This method is often used for testing hypertext links for validity, accessibility, and recent modification.")
Then it checks response. If response is valid or 405 (method not allowed), then the URL is marked as Valid.
Thus sometimes, if backend is not properly following RFC, you might get otherwise working URLs declared as Invalid during the test because of that improper HEAD response evaluation. Obviously, this is just a check for your convenience and you can ignore the check if you know the endpoint works for the methods and resources you need it to work.
So my advice would be to try ignoring the Test and just finishing setting up and publishing the API.
P.S. I am checking it on WSO2 API Cloud but behavior is identical to downloadable API Manager.

sharepoint object model in webservice

i am creating a webservice to provide one of the user poperty value to another application.
to do the same i am using sharepoint object model to connect to the mysite.
code : spsite site = new site(mysite url)
but i get the below error, kindly help.
error:
System.IO.FileNotFoundException: The Web application at "mysite url" could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
If this is a WCF service then by default there is no httpcontext, ergo, no spcontext. The fix is to enable "asp.net compatibility mode" in web.config. This is done with the following directive:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
I can think of two things that might be the cause of your problem:
-If your SharePoint is 64 bits, your application has to be built in 64 bit. The same applies for x86.
-The Target Framework option in your application needs to be set to 3.5
EDIT: I found an article about it. Maybe you could benefit from it.
http://blogs.technet.com/b/stefan_gossner/archive/2011/09/19/common-issue-new-spsite-returns-quot-the-web-application-at-http-server-port-could-not-be-found-quot.aspx

Microsoft.IdentityModel: Key not valid for use in specified state

I have a claims aware web application using Windows Identity Foundation that has been working well, except on one server. I am seeing the error message shown below in the event log.
Exception information:
Exception type: CryptographicException
Exception message: Key not valid for use in specified state.
at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
at Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)
This application is using a very standard implemenation of WIF with ADFS v2. It is not using RsaEncryptionCookieTransform. I am looking for any suggestions on how to diagnose this. Things I have tried so far:
The Application Pool is using the ASP.NET v4.0 identity which has the "Load User Profile" setting set to true.
I deleted the C:\Users\ASP.NET v4.0\AppData folder and saw this was successfully recreated.
I checked permissions on certificate private keys, which were good. I also tried disabling token encryption which did not make any difference.
Any advice would be appreciated.
This is usually caused by the application not being able to decrypt the authentication token cookie. Make sure that the identity that owns the App Pool has sufficient permission to access your certificate store. Try changing the Identity to NetworkService and see if that helps.
You should also clear your browser's cookies to make sure you don't have cookies from a different application cached.
The issue is 100% reproducible:
Indeed, after application being re-deployed, AND old authentication cookie is left on the client machine (client did not sign out) -this error appears to the client on any following request.
To fix this error client either has to delete the cookies and/or sign-in then sign-out from STS. Once all done - the error goes away and everything is fine until next upgrade....
After some research, I think this is a bug in the SessionAuthenticationModule that needs to be fixed. If you carefully look at the stack trace above, there is an interesting method called TryReadSessionTokenFromCookie, which sets expectation that authentication module will "try" to read the token from cookie, and will return false if this fails -here is the code (thanks to Resharper!):
public bool TryReadSessionTokenFromCookie(out SessionSecurityToken sessionToken)
{
byte[] sessionCookie = this.CookieHandler.Read();
if (sessionCookie == null)
{
sessionToken = null;
return false;
}
sessionToken = this.ReadSessionTokenFromCookie(sessionCookie);
if (DiagnosticUtil.TraceUtil.ShouldTrace(TraceEventType.Verbose))
{
DiagnosticUtil.TraceUtil.Trace(TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString("TraceValidateToken", new object[0]), new TokenTraceRecord(sessionToken), null);
}
return true;
}
Obviously, the code fails in this method with unhandled error and developer is left without any option to handle the error in more or less reasonable way. (...Or at least I could not find any, since this HTTP module does not pass this error onto HttpApplication object for handling, and throws it in the user's face.)
So, I think there are two bugs:
1) Security token handler needs to be more specific on the reasoning of thrown ID1073 (server side decryption error or wrong (old) cookie error)
2) There has to be a way for a developer to handle this error and sign-out the user, if it occurs. I'll take ANY help on this one...
Can anyone PLEASE create a sample code, showing how to intercept this exception so user can be automatically signed-out when this error occurs? Again, Application.Error event does not seem to get fired from this module -not sure what else can be done to handle it, other than writing my own SessionAuthenticationModule.
ANY HELP IS HIGHLY APPRECIATED!!!
Thanks!
Alex
I resolve my case because i have the same cookie name "FedAuth" for two applications (this is the name by default). Just put a different name and it's resolve :
<system.identityModel.services>
<federationConfiguration>
<cookieHandler name="ACookieName" />
</federationConfiguration>
The following worked for me:
You need to add section to system.identityModel/identityConfiguration
Reference:
SessionSecurityTokenHandler trying to decrypt SessionSecurityToken in RSA-encrypted cookie using DPAPI; why?
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<audienceUris>
<add value="yoursite.com" />
</audienceUris>
<issuerNameRegistry type="Thinktecture.IdentityModel.Tokens.MetadataBasedIssuerNameRegistry, Thinktecture.IdentityModel">
<trustedIssuerMetadata issuerName="urn:federation:company:stage" metadataAddress="https://federation-sts-stage.company.com/FederationMetadata/2007-06/FederationMetadata.xml"></trustedIssuerMetadata>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,
System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:
Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();
This error doesn't seem to be caught by http application.
Please check out http://social.technet.microsoft.com/wiki/contents/articles/1898.aspx#Q1 instead.
This issue is because of insufficient permission.
The app pool should have ApplicationPoolIdentity Identity to make it work.
Goto your apppool -> Advanced Settings -> Build-in accounts to change the settings

WCF Server Error. The content type text/html of the response message does not match the content type of the binding

I've got a WCF Service, which calls a webservice, running on my development IIS server (IIS 7). I've added it as a service reference to a C# Website Project and it adds fine.
However, when I try to call any of the service contracts, I get the following error:
The content type text/html
of the response message does not match
the content type of the binding
(text/xml; charset=utf-8). If using a
custom encoder, be sure that the
IsContentTypeSupported method is
implemented properly. The first 1024
bytes of the response were:
'Blocked Web
Page
thanks in advance
BB
The error message says it clearly: you're getting back an HTML page instead of your service response. Looking at the fragment of that page listed in the error message, you're probably not authroized to use that service.
Try to connect to the service URL in a browser - you should probably see a page explaining that you're not allowed to access the page. Most likely, this is a permissions issue.
You need to configure WCF Tracing and find out what's happening on the server side.

IIS6.0 - ASP.NET 4.0 - Default Content Page throwing Error message 401.2

We have a .NET application that was recently converted to .NET 4.0 and then published to IIS 6.0. When we trying going to the url without a page www.blahblahblah.com we get the following error:
Server Error in '/' Application.
Access is denied. Description: An
error occurred while accessing the
resources required to serve this
request. The server may not be
configured for access to the requested
URL.
Error message 401.2.: Unauthorized:
Logon failed due to server
configuration. Verify that you have
permission to view this directory or
page based on the credentials you
supplied and the authentication
methods enabled on the Web server.
Contact the Web server's administrator
for additional assistance.
We have IIS 6.0 site setup with a default content page going to "default.aspx". However, it seems IIS is not getting to the point of forwarding the url to this page. If we navigate directly to www.blahblahblah.com/default.aspx the page comes up with not issue and we all other functionality of the application works. If we roll back to the 3.5 version, the default page forwarding works as it should. Does anyone have any idea what is causing this?
I found the issue. Someone had put this (see below) in the authorization tag which prevented access to the website as a whole preventing IIS from forwarding to the default page, even though the page default.aspx had a location exception that allowed all users.
<authorization>
<deny users="*"/>
</authorization>