C
C#14mo ago
paulman176

❔ Unable to process post request with asp.net core

I am making use of a document processing component (https://ej2.syncfusion.com/react/documentation/document-editor/web-services/core), where i need to use asp.net core for some server dependencies such as importing a docx file into the documenteditor. My problem is that I don't know wheter my fetch method is not working (and maybe wrong usage of my endpoints) or that the asp.net core application is not even running correctly
5 Replies
paulman176
paulman17614mo ago
when i typed dotnet run it said:
Now listening on: http://localhost:5179
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/paulvanmierlo/Projects/Contractmanagement/Contractmanagement
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
Now listening on: http://localhost:5179
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/paulvanmierlo/Projects/Contractmanagement/Contractmanagement
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
Unknown User
Unknown User14mo ago
Message Not Public
Sign In & Join Server To View
paulman176
paulman17614mo ago
i succesfully figured out that the http responses are working because i created a simple get request to make sure i am able to get some response from my server ( a simple OK message) Tried it with swagger and postman and both responded with OK so maybe there is something wrong with how i am fetching the data? also this is my console log from within the browser:
OK response received
OK response received
for the sample get request i am using the same port as URL for the get request as for the post request i am still not able to perform this is the controller code:
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.DocumentEditor;
using System.IO;

[ApiController]
[Route("[controller]")]
public class ImportController : ControllerBase
{

[AcceptVerbs("Post")]
[HttpPost]
[EnableCors("AllowAllOrigins")]
[Route("Import")]
public string Import(IFormCollection data)
{
if (data.Files.Count == 0)
return null;
Stream stream = new MemoryStream();
IFormFile file = data.Files[0];
int index = file.FileName.LastIndexOf('.');
string type = index > -1 && index < file.FileName.Length - 1 ?
file.FileName.Substring(index) : ".docx";
file.CopyTo(stream);
stream.Position = 0;

WordDocument document = WordDocument.Load(stream, GetFormatType(type.ToLower()));
string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
document.Dispose();
return json;
}

private FormatType GetFormatType(string fileExtension)
{
if (string.IsNullOrEmpty(fileExtension))
throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
switch (fileExtension)
{
case ".docx":
return FormatType.Docx;
case ".doc":
return FormatType.Doc;
case ".rtf":
return FormatType.Rtf;
case ".txt":
return FormatType.Txt;
// Add more cases for other supported file extensions if needed
default:
return FormatType.Docx; // Default to a specific format if the extension is not recognized
}
}
}
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.DocumentEditor;
using System.IO;

[ApiController]
[Route("[controller]")]
public class ImportController : ControllerBase
{

[AcceptVerbs("Post")]
[HttpPost]
[EnableCors("AllowAllOrigins")]
[Route("Import")]
public string Import(IFormCollection data)
{
if (data.Files.Count == 0)
return null;
Stream stream = new MemoryStream();
IFormFile file = data.Files[0];
int index = file.FileName.LastIndexOf('.');
string type = index > -1 && index < file.FileName.Length - 1 ?
file.FileName.Substring(index) : ".docx";
file.CopyTo(stream);
stream.Position = 0;

WordDocument document = WordDocument.Load(stream, GetFormatType(type.ToLower()));
string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
document.Dispose();
return json;
}

private FormatType GetFormatType(string fileExtension)
{
if (string.IsNullOrEmpty(fileExtension))
throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
switch (fileExtension)
{
case ".docx":
return FormatType.Docx;
case ".doc":
return FormatType.Doc;
case ".rtf":
return FormatType.Rtf;
case ".txt":
return FormatType.Txt;
// Add more cases for other supported file extensions if needed
default:
return FormatType.Docx; // Default to a specific format if the extension is not recognized
}
}
}
and this is how i am fetching the data
DocumentEditorComponent.Inject(Toolbar);
export default function Documenteditor() {
// Function to handle the document import
const importDocument = (file) => {
const formData = new FormData();
formData.append('file', file); // Assuming you have a file object from an input field

fetch('https://localhost:7166/Import/Import', {
method: 'POST',
body: formData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error importing document');
}
})
.then((document) => {
console.log(document); // Handle the imported document data
})
.catch((error) => {
console.error('Error importing document:', error);
});
};

// Event handler for file input change
const fileInputOnChange = (event) => {
const file = event.target.files[0];
importDocument(file);
};

return (
<>
<input type="file" onChange={fileInputOnChange} />
<DocumentEditorContainerComponent id="container" height={'1000px'} enableToolbar={true}>
<Inject services={[Toolbar]} />
</DocumentEditorContainerComponent>
</>
);
}
DocumentEditorComponent.Inject(Toolbar);
export default function Documenteditor() {
// Function to handle the document import
const importDocument = (file) => {
const formData = new FormData();
formData.append('file', file); // Assuming you have a file object from an input field

fetch('https://localhost:7166/Import/Import', {
method: 'POST',
body: formData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error importing document');
}
})
.then((document) => {
console.log(document); // Handle the imported document data
})
.catch((error) => {
console.error('Error importing document:', error);
});
};

// Event handler for file input change
const fileInputOnChange = (event) => {
const file = event.target.files[0];
importDocument(file);
};

return (
<>
<input type="file" onChange={fileInputOnChange} />
<DocumentEditorContainerComponent id="container" height={'1000px'} enableToolbar={true}>
<Inject services={[Toolbar]} />
</DocumentEditorContainerComponent>
</>
);
}
Unknown User
Unknown User14mo ago
Message Not Public
Sign In & Join Server To View
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
❔ Socket connection in WPF applicationHello, I'm fairly new to the C# environment and there's something I can't figure out: I created a co❔ Force log out the user after account deletion with JWT bearer auth.Hello, I'm working on adding a feature that allows administrators to delete users. As things current✅ I updated to .NET 8 and now it broke...Hello i thought about .NET 8 and it has very usefull features so i want to update to it but sadly wh✅ Compiling ASP.NET 7 app using Github ActionsI am trying to compile my ASP.NET 7 application solution using Github actions but am getting the fol❔ How to handle a group of variables that need to stay together within a class?How should I handle a group of data that needs to stay together within a class? The data is a set of❔ .NET MAUI MVVM Navigation and pass Object to new page, Throw Exception: Missing methodProgram crash after this code ```[RelayCommand] async Task GoApartmentDetail(Apartment apart❔ .NET Maui Blazor: Render a Website inside the Application and get its cookies.Hello, how can I have a Webview inside the Application itself? It cannot be an iframe since I need t❔ run code on serverhow to run c# code on server...is vps is needed or simple hosting...which server is best in ur view❔ WPF Canvas starts getting choppy and laggy after drawing a long lineHello, I am making an application with a feature that lets you draw on the screen, however after dra❔ Camera Control with arrow key in Unity Engine doesn't work