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

How to assign the 'src' attribute to an HTML element using Node.js

I am currently using 'express' in Node.js and have implemented the following code to send a URL input into text: <form method="GET" action='/download' class="my-5"> <div class="form-group"> ...

Forcing the Empty Table message in jQuery DataTables post an AJAX request

My configuration for jquery-datatables includes a custom search filter that acts as both the standard keyword filter and a specific Item ID search using an ajax call to retrieve a value from the back end, which is then used to search a particular column in ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

Retrieve the rowid from the first column of a jqGrid row

I want the first column of my jqGrid to display the rowid number number | name | class 1 | A | acceptable 2 | B | good 3 | C | bad Alternatively, I would like to add a column like this (image) https://docs.google.com/file/d/0Bxi6bFcYZ_MgYTI1dUJCMWEtd0E/ ...

What is the proper way to declare a JavaScript variable using a hyphen symbol?

When it comes to evaluating a string like employee-count = 3, my main issue arises when dealing with variables that may not have a standard naming convention. While valid variable names pose no challenge, identifiers such as employee-count leave me slightl ...

Encountering Issue with Ionic Js After Upgrading Node to Version 4.1.1 on Windows Platform

Recently, I updated Node to version 4.1.1 and now I'm encountering an issue with Gulp: Error: libsass bindings not found. Have you tried reinstalling node-sass? I've attempted various solutions to no avail, including: Removing node_modules an ...

How to handle an empty data response in Angular 2's HTTP service

My ASP.NET web API has a simple method with the following test results: $ curl localhost:5000/Api/GetAllQuestions [{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}] However, I am encountering an issue in my Angular 2 HTTP serv ...

Retrieving information using getStaticProps

I'm currently working on a new function that pulls data from The Guardian API, but I've hit a roadblock with an error message. Below is the response that's being returned: Furthermore, presented here is the code snippet for the asynchronous ...

Checking for the presence of the key name "item[]" within an object in AngularJs

I currently have an object called "obj" with two keys: "goal" and "item[]". It looks like this: var obj = {goal:"abc",item[]:"def"}; These keys and values are dynamically generated. Now here's the problem - I need to determine if these keys exist ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

Issue with Passing 'key' Prop to React Component in a Mapped Iteration

https://i.sstatic.net/qeFKT.pngI'm struggling with adding a key prop to a React component in a mapped array within a Next.js project. The issue lies in a Slider component and an array of Image components being mapped. Even though I have provided a uni ...

Storing the rdflib.Graph data in a dictionary

I am facing an issue where I want to store an rdflib.Graph in the session dictionary of my Flask application for easy access in other route functions. Here is the relevant code: from rdflib import Graph from flask import Flask, session import os app = Fla ...

Why doesn't AngularJS update the view after changes in the Watch service?

I am currently working with AngularJS 1.4 and I am attempting to create a frontend cache collection that updates the view when new data is inserted. I have looked into solutions from various sources, including this one on AngularJS watch service object, bu ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

Unveiling the JSON data hidden within JSONP

Currently, I am working on parsing a JSON file with C# language. The data received from the server looks like this: loadData([ {"id":"id1","nm":"name1"}, {"id":"id2","nm":"name2"}, {"id":"id3","nm":"name3"} ]); To simplify the example, I have removed ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Adjust the height of the div element to match the screen height with AngularJS controller

Can someone please assist me in resolving this issue? I'm currently working on a div element that displays data (positioned on the left side of the screen). I want to add a scrollbar exclusively to this div. I managed to achieve this by using the fol ...

Utilize JavaScript to append a CSS class to a dynamic unordered list item anchor element

I am working with a list of ul li in a div where I need to dynamically add CSS classes based on the click event of an anchor tag. Below is the HTML structure of the ul li elements: <div class="tabs1"> <ul> <li class="active"> ...