The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked:

$http({
    url: 'default.aspx/GetPageHtml?file=' + JSON.stringify(selectedFile) + '&page=' + itemNumber,
    method: "GET",
    headers: { 'Content-Type': 'application/json' },
    data:''
}).then(function successCallback(response) {
    return response.d;
}, function errorCallback(response) {

});

However, when trying to call the same method as an iframe ng-src, it did not work:

<iframe ng-src="default.aspx/GetPageHtml?file=candy.pdf&page=1" style="height: 150px;"></iframe>

Upon inspecting this Http call through Google Chrome's Developers tools, I discovered that the Content-Type was showing as 'text/html', preventing it from hitting my WebMethod. You can view a screenshot of this issue here.

I searched extensively on Google and Stackoverflow but could not find a reason why I needed to provide Content-Type: 'application/json' in order to call my WebMethod.

Answer №1

After conducting further research on my initial question and exploring different avenues, I was able to come up with a solution. I decided to create a new WebForm called GetDocumentHtml.aspx where I could centralize the operations that were originally being performed in the GetPageHtml WebMethod.

Now, instead of using the previous URL structure:

default.aspx/GetPageHtml?file=candy.pdf&page=1

I am utilizing the new URL:

/GetDocumentHtml.aspx?file=calibre.docx&page=1

Within the Page_Load Method, I have implemented the following code to extract the parameters from the URL:

var file = GetValueFromQueryString("file");
var page = Convert.ToInt32(GetValueFromQueryString("page"));

The GetValueFromQueryString Method looks like this:

private String GetValueFromQueryString(String value)
{
    try
    {
        return Request.QueryString[value].ToString();

    }
    catch (System.Exception exp)
    {
        return String.Empty;
    }
}

I trust that this information will prove beneficial to others facing similar challenges. Thank you.

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

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

Adding list items to an unordered list without making them draggable using jQuery

How can I allow users to build a list of sports and drag them into a "cart" using jQuery? The issue I'm facing is that the appended list items are not draggable, and I'm unsure of how to solve this problem. /* JS code for sports.html */ $(fu ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

Attempting to remove the current click event listener and add a new event listener

I am attempting to remove the click event binding and replace it with another click event after the button has been clicked once. <small id="selectall_agriculture" onclick="refineSearch.testing('agriculture')">(select all)</small> O ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Error with top-level-await when integrating Firebase with Stripe Checkout session

I have been working on setting up a checkout session using the stripe firebase extension, but I encountered an error: ./pages/viewer.js Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enable it) F ...

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

I'm receiving a 404 error on my API route in next.js - what could be causing this

What could be causing the error message "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when attempting to fetch data from the sanity client? Here is a snippet of code from Rideselector.js: //"use client"; import Image from &apo ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Is there a way to prevent the Angular Material input counter from shifting from inside the input to outside when it loses focus?

After upgrading to the latest Angular Material Design version (1.0.0-rc4) from 0.11.4, I have encountered some issues with my forms. The problem arises when dealing with two inputs. Initially, the max-length counter is displayed inside the input before ei ...

Should I utilize Next.js API route or communicate directly with Firestore from the client side?

Greetings, I am new to Next.js and have a few queries regarding utilizing Firebase authentication on both the client side and server side. My project is set up with Firebase admin and client SDKs, and I have a signup page where users provide their name, em ...

Transmitting JSON data to a Flask template

I struggled to figure out how to retrieve JSON data from my search results, but I've managed to solve that issue. Now, the challenge is updating my jinja template with the data I fetched. Despite attempting various methods, my lack of experience with ...

Guide on returning a JSON response for validation in Laravel

Verification code $this->validate($request, [ 'email'=> 'required|email|unique:users', 'email'=> 'required|max:120', 'password' => 'required|min:4&apos ...

What could be the reason my Minecraft location_check predicate isn't executing?

I diligently followed numerous tutorials and successfully implemented the "player is_sprinting:true" predicate in my newly created datapack. This proves that my datapack is functioning properly. Despite my thorough research, I could not find any examples ...

Button triggered page refresh after Ajax content load

After using AJAX to load a page into a div, everything seems to be working as expected. However, I'm encountering an issue where clicking on buttons within the loaded content causes the entire page to refresh unexpectedly. This behavior is inconsisten ...

Utilize a single spa to load various AngularJS applications

After implementing single spa with angular 9, I followed the instructions provided in the following link: https://github.com/liuyiba/Single-spa-angular-cross-domain. This setup involves coexisting apps. My objective is to embed one angular app within anoth ...

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...