I have an ASP.NET MVC 5 Application, which handles requests from my web site made with the fetch API. When an exception occurred in my controller, I use my custom "OnException" method, overriden from System.Web.Mvc.Controller, to send a result in JSON, containing data about the error. I do this because I don't want to send the default HTML error page. In this method, which is global for all controllers, I need to check if the request has been performed with the fetch API (if not, I don't do anything).
How can I do this ?
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
To fetch a user we need: fetch('https://api.github.com/users/USERNAME') . If the response has status 200 , call . json() to read the JS object. Otherwise, if a fetch fails, or the response has non-200 status, we just return null in the resulting array.
Either of a specific header or a specific parameter would work; the "clean" approach would probably be to set the "Accept:" header in the fetch-sent request to "application/json", signalling that the said request is looking for a JSON response, and use that on the server-side to determine whether to send JSON or HTML.
I think Accept Header does not help for the all scenarios. If you request HTML and you have a layout system and want to disable it for async request you will need a different approach.
Using a custom flag header is a more guarantied approach I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With