Invalid Content Type when calling a POST api from azure logic app - azure

I have created a Web API using .net core to POST file (excel).
When attaching the file from the post man it is working as expected but now I am trying to do the same using Azure logic app.
I am using a FTP connector and reading the file from it and then calling the REST api, the end point is getting hit but however I am unable to get the file data.
I am very much new to logic apps and tried to find a lot but no luck.
Web API
[HttpPost("x")]
public async Task<IActionResult> MigrateHistoricalData()
{
int filesCount = HttpContext.Request.Form.Files.Count;
if (filesCount > 0)
{
var file = HttpContext.Request.Form.Files[0];
if (file != null && file.Length > 0)
{
// other logic
}
}
else
{
return new BadRequestObjectResult("No files found in the request.");
}
return null;
}
Error Image:

You could update your browser to the latest version and have a try.
It's a MVC bug, and on 13th of September 2018 Microsoft has implemented a fix for this issue, and it will be released with in ASP.NET Core 2.2.

Set content-type of the HTTP request header to multipart/form-data in the Logic App and see if that helps Logic App Http Connector Header

Related

Get HttpStatusCode 504 ( DNS Name Not Found ) in .Net Core 2.1 and Upper Version

I was create simple project with .netCore 2.0 and send HttpRequest with HttpClient, that is working well.
But, when I'm migrating from .netCore 2.0 to upper version ( e.g: .NetCore 2.1 or .netCore 3.0 ) this Code is not working.
My Code is:
public async Task<bool> IsValid()
{
string url = "http://api.domain.com/...";
var values = new Dictionary<string, string>()
{
{ "param1", "value1" },
{ "param2", "value2" }
};
HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(values);
var post = await client.PostAsync(url, content);
if (post.StatusCode == System.Net.HttpStatusCode.OK)
{
return true;
}
return false;
}
I expect the output of httpResponse to bo HttpStatusCode.OK. but the actual output is HttpStatusCode.GatewayTimeout.
I found that:
If I run API server ( http://api.domain.com/ ) in IIS of windows server 2012, all requests is working well.
But When I Use IIS of Windows 8, only HttpRequest with ASP.NET Core sdk 2.0 is working and others not working.
Can anyone help me?
This problem has finally been resolved.
This problem was related to the network and proxy settings in my network.
I realize when api server be in internet network, that is working well. but when api server to be used in local network, Because of using the proxy in my network, all
requests was encountered with error 504 (unless the request was sending with .netCore sdk 2.0 ).
It should be noted I had added this line 192.168.11.125 api.domain.com to host file in Directory c:\windows\system32\drivers\etc\hosts.
and also, I had added Follow Exceptions:
192.168.11.125 api.domain.com
from path:
Control Panel > Network and Internet > Internet Option > Connections Tab > Lan Settings > Advanced > Exceptions panel
But that's not working.
When I picked up the check of Use a proxy server for your lan ... in Local Area Network (LAN) Settings form, all requests working well.
Of course, this question remains that, why The same request is working with .netcore sdk 2.0 ?
what is difference between sending request with .netCore sdk 2.0 and (.netCore sdk 2.1 or .netCore sdk 2.2 or .netCore sdk 3.0)???!!!
Good luck.

problems uploading xslx file in body of post request to .net core app on aws-lambda

I'm trying to send a post request with postman to our AWS-Lambda server. Let me first state that, when running the web-server on my laptop using the Visual studio debugger, everything works fine. When trying to do exactly the same but to the url of the AWS-Lambda i'm getting the following errors when shifting through the logging:
when uploading the normal xlsx file (it's a size of 593kb)
Split or spanned archives are not supported.
When uploading the same file but with a few worksheet removed (because i thought maybe the size is to big, which should be bs but lets try):
Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory.
when uploading a random xlsx file:
Offset to Central Directory cannot be held in an Int64.
I do not know what is going on, it might have something to do with the way postman serializes the xlsx file and the way my debug session (on a windows machine) deserializes it which is different from the way AWS-Lambda deserializes it but that's just a complete guess.
I always get a 400 - Bad Request response
I'm at a loss and am hoping someone here knows what to do.
This is the method in my controller, however the problem occurs before this:
[HttpPost("productmodel")]
public async Task<IActionResult> SeedProductModel()
{
try
{
_logger.LogInformation("Starting seed product model");
var memoryStream = new MemoryStream();
_logger.LogInformation($"request body: {Request.Body}");
Request.Body.CopyTo(memoryStream);
var command = new SeedProductModelCommand(memoryStream);
var result = await _mediator.Send(command);
if (!result.Success)
{
return BadRequest(result.MissingProducts);
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return BadRequest();
}
}
postman:
we do not use api keys for our test environment
Since you are uploading binary content to API Gateway, you need to enable it through the console.
Go to API Gateway -> select your API -> Settings -> Binary Media Types -> application/octet-stream, like the image below
Save it and make sure to redeploy your API, otherwise your changes will have no effect.
To do so, select your API -> Actions -> Deploy API

Swagger not working on Azure Web app running as OWIN

I have a ASP.NET Web API implemented as OWIN middleware. I hosted it on azure and now I have a problem using swagger. It is perfectly working on localhost but when I try it on azure I get this:
The way I did my configuration for swagger on the API was to completely remove SwaggerConfig.cs file and add all the configuration into my Startup.cs class as shown here: How to generate documentation using swashbuckle for WebApi 2 with Owin . If it is going to help, I am trying to implement oAuth2 between my API, identity server and client application.
Can you help me find out what is the reason for not getting swagger functionality on Azure?
EDIT: I also tried the solution from here but without success. I went to my API->Properties->Buld tab->Changed to 'Release' configuration->In the output path added the same what was in the 'Debug' configuration and nothing.
My bin folder on Azure:
I had this problem myself when going though this tutorial.
In that tutorial on #3 under "Configure the middle tier to call the data tier" I named my key apiAppURL instead of toDoListDataAPIURL. This caused me to get 500 response codes and
{
"Message": "An error has occurred."
}
in the response body.
I fixed it by updating the following line:
var client = new ApiApp(new Uri(ConfigurationManager.AppSettings["toDoListApiURL"]));
to
var client = new ApiApp(new Uri(ConfigurationManager.AppSettings["apiAppURL"]));
**The change made was to the string at the end of the line. That code can be found in ToDoListController.cs on line 42
Hope this helps someone!
Check your SwaggerConfig.cs file, if you are not included the xml file with your swagger, it works in your azure app services.
c.IncludeXmlComments($#"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApiSwagger.XML");
c.DescribeAllEnumsAsStrings();
I've included these 2 lines of code to show my xml in the swagger, the azure swagger will gone error.
This is late reply but may help someone in future.
I solved this issue this way:
Set XML documentation file path in project settings to : wwwroot\api.xml
Let Swagger know where the file is within ConfigureServices method in
Startup.cs:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = "api.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, "wwwroot", xmlFile);
c.IncludeXmlComments(xmlPath);
});
You can set different paths but you will get the idea of how to do it from this example.

windows azure blob leasing in sdk1.4

I have been using the following code which I wrote after consulting the following thread - Use blob-leasing feature in the Azure cloud app
public static void UploadFromStreamWithLease(CloudBlob blob, Stream src, string leaseID)
{
string url = blob.Uri.ToString();
if (blob.ServiceClient.Credentials.NeedsTransformUri)
{
url = blob.ServiceClient.Credentials.TransformUri(url);
}
HttpWebRequest req = BlobRequest.Put(new Uri(url), 90, blob.Properties, BlobType.BlockBlob, leaseID, 0);
BlobRequest.AddMetadata(req, blob.Metadata);
using (var writer = new StreamWriter(req.GetRequestStream()))
{
byte[] content = new byte[src.Length];
writer.Write(readFully(src));
}
blob.ServiceClient.Credentials.SignRequest(req);
req.GetResponse().Close();
}
The readFully() method above simply gets the content from the stream to a byte[] array.
I have been using this code to upload some stuff to any blob that has a valid leaseId. This was working fine until I moved to version 1.4 of the Azure SDK. In the new version of the azure sdk, I get an error 400 in req.GetResponse() method.
Can someone please point out what has changed in azure sdk 1.4 that's screwing this up?
Thanks
Kapil
The 400 code means "bad request" there should be some additional error message, see http://paulsomers.blogspot.com/2010/10/azure-error-400-bad-request.html for some examples. You should try debugging or sniffing the network to get the error message.
There were some bugs for downloading blobs in version 1.4, but they may not affect you. However, you should upgrade to latest version.

Upload a file to SharePoint through the built-in web services

What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?
Following the two initial answers...
We definitely need to use the Web Service layer as we will be making these calls from remote client applications.
The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.
There is additionally a web service to upload files, painful but works all the time.
Are you referring to the “Copy” service?
We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?
I have posted our code as a suggested answer.
Example of using the WSS "Copy" Web service to upload a document to a library...
public static void UploadFile2007(string destinationUrl, byte[] fileData)
{
// List of desination Urls, Just one in this example.
string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };
// Empty Field Information. This can be populated but not for this example.
SharePoint2007CopyService.FieldInformation information = new
SharePoint2007CopyService.FieldInformation();
SharePoint2007CopyService.FieldInformation[] info = { information };
// To receive the result Xml.
SharePoint2007CopyService.CopyResult[] result;
// Create the Copy web service instance configured from the web.config file.
SharePoint2007CopyService.CopySoapClient
CopyService2007 = new CopySoapClient("CopySoap");
CopyService2007.ClientCredentials.Windows.ClientCredential =
CredentialCache.DefaultNetworkCredentials;
CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Delegation;
CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result);
if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success)
{
// ...
}
}
Another option is to use plain ol' HTTP PUT:
WebClient webclient = new WebClient();
webclient.Credentials = new NetworkCredential(_userName, _password, _domain);
webclient.UploadFile(remoteFileURL, "PUT", FilePath);
webclient.Dispose();
Where remoteFileURL points to your SharePoint document library...
There are a couple of things to consider:
Copy.CopyIntoItems needs the document to be already present at some server. The document is passed as a parameter of the webservice call, which will limit how large the document can be. (See http://social.msdn.microsoft.com/Forums/en-AU/sharepointdevelopment/thread/e4e00092-b312-4d4c-a0d2-1cfc2beb9a6c)
the 'http put' method (ie webdav...) will only put the document in the library, but not set field values
to update field values you can call Lists.UpdateListItem after the 'http put'
document libraries can have directories, you can make them with 'http mkcol'
you may want to check in files with Lists.CheckInFile
you can also create a custom webservice that uses the SPxxx .Net API, but that new webservice will have to be installed on the server. It could save trips to the server.
public static void UploadFile(byte[] fileData) {
var copy = new Copy {
Url = "http://servername/sitename/_vti_bin/copy.asmx",
UseDefaultCredentials = true
};
string destinationUrl = "http://servername/sitename/doclibrary/filename";
string[] destinationUrls = {destinationUrl};
var info1 = new FieldInformation
{
DisplayName = "Title",
InternalName = "Title",
Type = FieldType.Text,
Value = "New Title"
};
FieldInformation[] info = {info1};
var copyResult = new CopyResult();
CopyResult[] copyResults = {copyResult};
copy.CopyIntoItems(
destinationUrl, destinationUrls, info, fileData, out copyResults);
}
NOTE: Changing the 1st parameter of CopyIntoItems to the file name, Path.GetFileName(destinationUrl), makes the unlink message disappear.
I've had good luck using the DocLibHelper wrapper class described here: http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html
From a colleage at work:
Lazy way: your Windows WebDAV filesystem interface. It is bad as a programmatic solution because it relies on the WindowsClient service running on your OS, and also only works on websites running on port 80. Map a drive to the document library and get with the file copying.
There is additionally a web service to upload files, painful but works all the time.
I believe you are able to upload files via the FrontPage API but I don’t know of anyone who actually uses it.
Not sure on exactly which web service to use, but if you are in a position where you can use the SharePoint .NET API Dlls, then using the SPList and SPLibrary.Items.Add is really easy.

Resources