An unhandled exception has occurred: Malformed URL in Release mode in .net core 2.0 app - release

I have a .net core 2.0 app which uses IdentityServer 4. it works perfectly in development mode. then I published it for production mode and tested. when I click a (that action has a method to generated accesstoken) link I got an error like below,
An unhandled exception has occurred: Malformed URL
then error occurs here in production(Release) mode:
var disco = await IdentityModel.Client.DiscoveryClient.GetAsync(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value);
above DiscoveryClient is http not https
here is the full description of the error ..
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Malformed URL
System.InvalidOperationException: Malformed URL
at IdentityModel.Client.DiscoveryClient.ParseUrl(String input)
at IdentityModel.Client.DiscoveryClient..ctor(String authority, HttpMessageHandler innerHandler)
at IdentityModel.Client.DiscoveryClient.<GetAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
is this because 'https'. I have no idea what is happening.hope your help with this.

This is a pretty old post, but it still might help someone. I had this exact same issue, only that the URL that I was passing in was perfectly fine. The problem on my side was that the IdentityServer Authority URL was misconfigured, causing it to throw the same exception.

Here is code snippet from DiscoveryClient's ParseUrl showing when it throws that exception:
public static DiscoveryEndpoint ParseUrl(string input)
{
var success = Uri.TryCreate(input, UriKind.Absolute, out var uri);
if (success == false)
{
throw new InvalidOperationException("Malformed URL");
}
if (!DiscoveryEndpoint.IsValidScheme(uri))
{
throw new InvalidOperationException("Malformed URL");
}
Here is the code for DiscoveryEndpoint's IsValidScheme method:
public static bool IsValidScheme(Uri url)
{
if (string.Equals(url.Scheme, "http", StringComparison.OrdinalIgnoreCase) ||
string.Equals(url.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
Based on this the exception is not thrown because the url is using http.
Try calling
new Uri(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value, UriKind.Absolute)
before your call to 'IdentityModel.Client.DiscoveryClient.GetAsync' so that you can see what exception is thrown by the Uri constructor.

Related

Face Detection in Azure

I am trying to experiment with the Microsoft Azure Cognitive Services Face Detection. I am doing something wrong. I am trying to use the C# SDK for face detection. I am getting the error below. I have no idea how to even debug this or what the error message is telling me. Its almost like something I have set is not coming through, but I am just guessing.
Microsoft.Azure.CognitiveServices.Vision.Face.Models.APIErrorException
HResult=0x80131500
Message=Operation returned an invalid status code 'BadRequest'
Source=Microsoft.Azure.CognitiveServices.Vision.Face
StackTrace:
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperations.<DetectWithUrlWithHttpMessagesAsync>d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperationsExtensions.<DetectWithUrlAsync>d__4.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at BWD.ASPNET.Core.Services.FaceDetection.<DoWork>d__5.MoveNext() in
My code for making this call is:
string faceEndpoint = "https://eastus.api.cognitive.microsoft.com";
FaceAttributeType[] faceAttributes =
{ FaceAttributeType.Age, FaceAttributeType.Gender, FaceAttributeType.Hair,
FaceAttributeType.Smile, FaceAttributeType.Gender, FaceAttributeType.Emotion, FaceAttributeType.FacialHair,
FaceAttributeType.Accessories };
FaceClient faceClient = new FaceClient( new ApiKeyServiceClientCredentials(connString), new System.Net.Http.DelegatingHandler[] { });
faceClient.Endpoint = faceEndpoint;
var ctx = new BWDContext();
var pics = await (from p in ctx.Picture where p.DateOfFacial == null select p).ToListAsync();
foreach(var pic in pics)
{
if(Uri.IsWellFormedUriString(pic.PicFileUrl, UriKind.Absolute))
{
IList<DetectedFace> faceList =
await faceClient.Face.DetectWithUrlAsync(pic.PicFileUrl, true, true, faceAttributes); // error occurs here
.....on and on .......
I also tried making a rest call with fiddler, which does work. On the fiddler call, I just do a post to this url: https://eastus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise
My header is:
User-Agent: Fiddler
Ocp-Apim-Subscription-Key: ....subscription key......
Content-Type: application/json
Host: eastus.api.cognitive.microsoft.com
Content-Length: 107
My post body is:
{ 'url': 'https://bwdpictures.blob.core.windows.net/bwdpictures/d916acdd-ab9f-429e-8b75-6d5f9206a9b4.jpg' }
I get a result back from the rest call in fiddler.
I'm sure that the problem is something with my code, but I have no idea what the issue is. If you have some suggestions, I would appreciate it.
TIA,
Wally
Bingo. The problem was that I had the Gender attribute in the face attributes twice. I just noticed it. When I took the second one out, the problem was solved. Sorry for the post.

Why am I getting javax.xml.bind.UnmarshalException when calling a soap web service

I am trying consume a SOAP web Service and I have written my SOAP client using Spring-ws. This also included a message signing. However when I am trying to trigger a request I am getting the exception. From the server standpoint, the server is sending a successful response but I am not able to unmarshall it.
I followed quite a few suggestion including one from this
UnmarshallingFailureException, unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault")
Following the above link however removed the exception but in turn I am getting a null response object and I could not trace out where the response went missing.
This is my Config class methods:
public WebServiceTemplate accountsInquiryWebServiceTemplate() throws Exception {
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
Jaxb2Marshaller accountsInquiryMarshaller = accountsInquiryMarshaller();
webServiceTemplate.setMarshaller(accountsInquiryMarshaller);
webServiceTemplate.setUnmarshaller(accountsInquiryMarshaller);
ClientInterceptor[] clientInterceptors = new ClientInterceptor[1];
clientInterceptors[0] = wsClientSecurityInterceptor();
webServiceTemplate.setInterceptors(clientInterceptors);
webServiceTemplate.setCheckConnectionForFault(true);
webServiceTemplate.setDefaultUri(serviceURL);
return webServiceTemplate;
}
private Jaxb2Marshaller accountsInquiryMarshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPaths(new String[]{
"com.accounting.integrationservice"
});
return jaxb2Marshaller;
}
private Wss4jSecurityInterceptor wsClientSecurityInterceptor() throws Exception {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("Signature");
wss4jSecurityInterceptor.setSecurementUsername(username);
wss4jSecurityInterceptor.setSecurementPassword(password);
wss4jSecurityInterceptor.setSecurementSignatureCrypto(clientCrypto());
wss4jSecurityInterceptor.setValidationActions("Signature");
return wss4jSecurityInterceptor;
}
private Crypto clientCrypto() throws Exception {
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
cryptoFactoryBean.setKeyStoreLocation(resourceLoader.getResource("classpath:accountsInquiry/keystore/" + keyStoreLocation));
cryptoFactoryBean.setKeyStorePassword(keyStorePassword);
cryptoFactoryBean.afterPropertiesSet();
return cryptoFactoryBean.getObject();
}
The client calls as below:
Response response = accountsWebServiceTemplate.marshalSendAndReceive(request);
The exception stack that I am getting is as below : Its similar to the referred link above, so not putting the entire exception stack
org.springframework.ws.soap.security.AbstractWsSecurityInterceptor.handleResponse(AbstractWsSecurityInterceptor.java:247)
- Could not validate request: No WS-Security header found
org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). Expected elements are http://www.qualityaccounts.com/IntegrationService/schemas/ProductInfo/v1}
at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:911)
at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:784)
at org.springframework.ws.support.MarshallingUtils.unmarshal(MarshallingUtils.java:62)
at org.springframework.ws.client.core.WebServiceTemplate$3.extractData(WebServiceTemplate.java:413)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:619)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
Ok So, I was trying to use "Signature" to validate the Security Header of the response even though there was no header. But thing is if I didn't specify the ValidationAction it was throwing NullPointerException so it was expecting at least one ValidationAction.
To counter all this I told the Spring security not to validate the response by this piece of code.
wss4jSecurityInterceptor.setValidateResponse(false);
Thanks to this article
Spring Security - Wss4jSecurityInterceptor - Nullpointer

Azure storage CloudBlockBlob.PutBlockAsync() The value for one of the HTTP headers is not in the correct format.

I'm developing a web site with backend web api ASP.NET CORE 2.1 and frontend angular 6.
In this site I'm integrating upload of large files through web api with microsoft.azure.storage 9.3.2. I'm doing this chunking by blocks, and sending them from FE to an endpoint. Inside I do the following logic:
var container = CloudStorageAccount.Parse(key).CreateCloudBlobClient().GetContainerReference(containerName);
var result = await container.CreateIfNotExistsAsync();
if (result)
{
await container.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
BlockBlob = container.GetBlockBlobReference(blobName);
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
And I have an exception here that says " The value for one of the HTTP headers is not in the correct format."
the stackTrace is:
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.d__4`1.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Core\Executor\Executor.cs:line 316
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.d__62.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Blob\CloudBlockBlob.cs:line 1020
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at vidiwin2Api.Controllers.VideosController.d__18.MoveNext() in D:\repos\vidiwin2api\vidiwin2Api\Controllers\VideosController.cs:line 469
The most amazing is that I had the same functionality in an older version, with BE web api on Framework 4.6 and microsoft.azure.storage 6.0.0, and this works!!
I have tested all kind of params in PutBlockAsync and allways the same exception.
Can anyone helps me please?
I had the same error because i forgot to reset the stream position to 0 before calling PutBlockAsync(). Try
chunkStream.Position = 0;
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
Otherwise inspect the ExtendedErrorInformation property on the Exception. There you will find additional information about the wrong HTTP header.

How to catch HttpRequestValidationException

How can i redirect the user to a custom error page, when HttpRequestValidationException occurred.
I tried to catch it in my basecontroller :
protected override void OnException(ExceptionContext exceptionContext)
{
if (exceptionContext.Exception is HttpRequestValidationException)
{
this.View("CustomError").ExecuteResult(this.ControllerContext);
}
}
But i still get the exception :
A potentially dangerous request.form value was detected from the client
This exception occurs much earlier in the execution of the request and cannot be handled by the OnExceptionmethod in a base controller. You could write a global exception handler as I showed in this post.

Why does IIS return a 500 status code when the server times out?

We're running IIS7 & .net 4.0. When the server times out due to a long running request, the error page is shown, but the error code is just 500 rather than 408 or possibly 503 that I'm expecting. We want to show a different error page if it's a timeout, but I can't configure this in the <customErrors> section if it's just giving a 500 error. Is this a configuration issue?
You can add code like this into your global.asax.cs
public class Global : System.Web.HttpApplication
{
protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = HttpContext.Current.Server.GetLastError();
if (ex != null && ex is HttpException && ex.Message == "Request timed out.")
{
HttpContext.Current.Response.StatusCode = 503;
HttpContext.Current.Response.End();
}
}
}
I found this to not work properly and still return a 500 error without the Response.End() in there. Given your question, I'm not sure if you want to do a redirect instead to show an error page that would itself output the 503 instead of in the above.
Its really ASP.NET returning the 500 status, IIS is just passing it along.

Resources