Issue with loading 3D model using three.js in a web browser

While using ASP.Net core, I encountered an issue with loading a 3D model using the Three.js library. The error message "ERR_NAME_NOT_RESOLVED" appears when trying to load the scene. You can view the code in my VS View here. This code works perfectly in VS CODE but fails to load in my ASP.NET Core APP. You can check out my VS project here.

Here is an excerpt from my Controller:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PetStore.Web.Models;

namespace PetStore.Web.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

//The action used for the View

        public IActionResult TestView()
        {
            return View();
        }
    }
}

Below is the code snippet from the View used to render the model:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>3D model </title>
</head>

<body>
*//Js Libraries*
    <script src="~/js/three.js"></script>
    <script src="~/js/GLTFLoader.js"></script>
    <script src="~/js/OrbitControls.js"></script>

    <div class="container">
        <script>
            // JavaScript Document

            var scene = new THREE.Scene();
            scene.background = new THREE.Color(0xdddddd);
*//Position the camera for the view*
            var camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 5000);
            camera.rotation.y = 45 / 180 * Math.PI;
            camera.position.x = 800;
            camera.position.y = 100;
            camera.position.z = 1000;

*//Render the model using WebGl*
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);

*//Add rotation for the model*
            let controls = new THREE.OrbitControls(camera, renderer.domElement);
*//Add light to the scene*
            var hlight = new THREE.AmbientLight(0x404040, 100);
            scene.add(hlight);
            directionalLight = new THREE.DirectionalLight(0xffffff, 100);
            directionalLight.position.set(0, 1, 0);
            directionalLight.castShadow = true;
            scene.add(directionalLight);
            light = new THREE.PointLight(0xc4c4c4, 10);
            light.position.set(0, 300, 500);
            scene.add(light);
            light2 = new THREE.PointLight(0xc4c4c4, 10);
            light2.position.set(500, 100, 0);
            scene.add(light2);
            light3 = new THREE.PointLight(0xc4c4c4, 10);
            light3.position.set(0, 100, -500);
            scene.add(light3);
            light4 = new THREE.PointLight(0xc4c4c4, 10);
            light4.position.set(-500, 300, 500);
            scene.add(light4);

*//Load the Model*
            let loader = new THREE.GLTFLoader();
            loader.load('../drawings/Fireplace/scene.gltf', function (gltf) {
                car = gltf.scene.children[0];
                car.scale.set(0.5, 0.5, 0.5);
                scene.add(gltf.scene);
                animate();
            });
            function animate() {
                requestAnimationFrame(animate);
                renderer.render(scene, camera);
            }
            animate();
        </script>
    </div>

</body>
</html>

Answer №1

Your assumption that the issue lies in the path provided seems to be accurate. It is probable that ASP.NET Core does not recognize the path to the model file in the 'Startup.cs' file within the root of your 'PetStore.Web' project.

A 404 error for a static file in ASP.NET Core can be due to one or both of the following reasons:

  1. Your application is serving static files outside of the project's web root directory.
  2. ASP.NET Core does not recognize the file content type of the requested static file.

Even if the model files are stored within the web root directory, it is essential for your web app to map the model file extensions (.glb, .gltf) to their corresponding IANA registered MIME content types ("model/gltf+binary", "model/gltf+json") for ASP.NET Core to serve them to a client.

Include the 'model file extension to MIME content type' mappings in the Configure method of the Startup.cs file in your 'PetStore.Web' project.

 public void Configure(IApplicationBuilder app)
 {
     app.UseStaticFiles(); // For the wwwroot folder

     // ADD the following...

     // Set up custom content types - associating file extension to MIME type
     // Include the following 'using' statement:
     // using Microsoft.AspNetCore.StaticFiles;
     FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();

     // The MIME type for .GLB and .GLTF files are registered with IANA under the 'model' heading
     // https://www.iana.org/assignments/media-types/media-types.xhtml#model
     provider.Mappings[".glb"] = "model/gltf+binary";
     provider.Mappings[".gltf"] = "model/gltf+json";

     app.UseStaticFiles(new StaticFileOptions
     {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
        RequestPath = "/StaticFiles",
        ContentTypeProvider = provider
    });
 }

Based on the image folder structure you referenced, update the paths in the code sample as follows:

FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), "Scanes/Fireplace")),
RequestPath = "/Scanes/Fireplace",

Following these changes, the request to the static model file by three.js should be successful:

loader.load('/Scanes/Fireplace/scene.gltf', function (gltf) {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

determine if the req.params parameter is void on an express route

Hi everyone, I'm a beginner with node and express and could really use some guidance. I am currently attempting to create a get request that checks if the req.params.address_line is empty, and then performs an action based on that condition. However, ...

Selenium is encountering a maximum call stack size error while attempting to access Highcharts

This particular issue is a bit complex. My goal is to retrieve highchart data from a selenium-controlled Chrome browser using the driver.execute_script method and injecting some JavaScript: driver.execute_script("return $('#chartID').highcharts( ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Node.js Timer Functionality for Precision Timing

I'm currently in the process of developing a live chess application and one feature I'm looking to incorporate is a timer. The challenge I'm facing lies in ensuring the timer is accurate. After conducting various tests, I discovered that bot ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

invoke two JavaScript functions without displaying any message

I'm facing an issue with Ajax as it's not displaying the message I intend to show. Let me elaborate. Within my PHP code, there is an input tag: <input type="submit" id="login_button_add" name="submit" value="Add" onclick="add_building(); sho ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

Detecting User Interaction with Email Link

On my webpage, there is a link that when clicked, opens the default Email client. I also want to track in my database if the user has clicked on this link or not. Since this interaction occurs at the client-side, I am wondering if there is a way to check ...

C# - Generating various lists depending on integer input in Console

I am interested in creating multiple lists based on a specific size. This can be achieved using the following code snippet : int Size = int.Parse(Console.ReadLine()); for (int i = 0; i < Size; i++) { List<string> ListName + i = new List<str ...

Utilizing data retrieval caching in nextjs getServerSideProps() for optimized performance

I am currently developing an application using nextjs that retrieves data from a firebase firestore. The issue I am facing is that the application makes these requests on every page load, even when the data does not need to be completely up to date. To add ...

Fulfill a promise based on a particular event in Puppeteer

I am looking for a way to seamlessly continue my puppeteer code after a particular event occurs. Specifically, I need guidance on how to handle the 'request' event in a synchronous manner. Here is an example of the event code: await page.on(&apo ...

Dealing with unhandled exceptions while passing promises into pg-promise batch transactions

Currently, I am diving into the realm of learning express and pg promise. However, during this journey, I have encountered a puzzling issue that I suspect stems from my somewhat shaky understanding of promises. Essentially, I have crafted some functions f ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

The error "map is not a function" occurs when trying to update the

I've encountered an issue with my links rendering on a page. I wrote a function that toggles a specific property from false to true based on whether the link is active or not, triggered by a click event. Upon inspecting the updated set of links, I no ...

Switching off toggle does not switch back to primary theme when clicking again for the second time

When I click the button for the first time, it changes the theme. However, when I click it a second time, nothing happens; it seems like it's stuck on the second theme forever. It should change themes with every click. Can someone please help me with ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Is there a way to attach an event listener to a span that was inserted using DTColumnBuilder?

I am attempting to include an onclick event for a span element that is generated by DTColumnBuilder. DTColumnBuilder .newColumn('Invoice') .withTitle('<span class="li-table-head ...