Transform JavaScript AJAX to HttpWebRequest implementation code

Is it possible to mimic an AJAX call to a web service within a console application using HttpWebRequest?

Here is the source request:

var webRequest = Sys.Net.WebServiceProxy.invoke('', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSuccess, onFailure, userContext, timeout, enableJsonp, jsonpCallbackParameter);

Below is a sample code snippet that attempts to do this but is not functional:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://webserver.com/WS_Message.asmx/MyMethod");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

byte[] _bytes= Encoding.UTF8.GetBytes("{p1:aa,p2:bb,p3:123}");

request.ContentLength = _bytes.Length;

Stream stream = request.GetRequestStream();
stream.Write(_bytes, 0, _bytes.Length);
stream.Close();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    Console.WriteLine(reader.ReadToEnd());
}

Answer №1

If you're utilizing a (.NET-based) web service in JavaScript, have you considered adding a web reference to your console app instead of manually recreating the web service call with HttpWebRequest? It could save you a lot of time and effort.

By simply adding a web reference, you can easily call the web service without the need for manual replication using HttpWebRequest.

Answer №2

After encountering some difficulties, I resorted to checking the correct http headers using Chrome Developer Console. It turns out the problem stemmed from an incorrect JSON string format.

The JSON string looked like this: @"{""p1"": ""aa"", ""p2"": ""bb"", ""p3"": 123}"

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 approach should be taken to effectively handle numerous tasks at the same time?

After learning about the numerous benefits of asynchronous programming, I finally decided to delve into the world of asyncs, Tasks, and awaits. My first project involved creating a simple class to handle multiple concurrent POST operations to my Web API. ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

Generate a blank image using the canvas.toDataURL() method

I've been attempting to take a screenshot of this game, but every time I try, the result is just a blank image. var data = document.getElementsByTagName("canvas")[0].toDataURL('image/png'); var out = document.createElement('im ...

Unexpected behavior: Model property not binding after .Net Core Ajax form submission

I am facing an issue with my .Net Core web project that involves form ajax submission. When I load the form, I set all property values to the view model. However, when I submit the form, only the properties bound to the HTML input are returned while the re ...

If the width of the window is below 768px, do not execute the function

In order to prevent the showCover() function from firing when the window width is less than 768px on page load AND resize, I have made some adjustments to the code below. Even though the window is smaller than 768px, the function will not be triggered. ...

What is the best way to transform this PHP Object into an array?

I am working with a Javascript array that needs to be passed to a PHP script using Ajax. Inside file.js: var params = {}; params["apples"] = "five"; params["oranges"] = "six"; params["pears"] = "nine"; var ajaxData = {data : params}; fetchData(ajaxData); ...

Create an array mapping of locations and convert each location to its corresponding language

With Next.js, I have successfully retrieved the current locale and all available locales for a language selection menu: const {currentLocale, availableLocales} = useContext(LangContext); // currentLocale = "en-US" // availableLocales = ["en- ...

There seems to be an internal server error occurring after attempting to post with a

While implementing ajax and web methods, I encountered an error message that says: post POST 500 (Internal Server Error) even though the path exists!!! This is the code I am currently using: function fnSendID() { $.ajax({ type: "PO ...

Revolutionary Knockout-Kendo MultiSelect Feature: Pressing Enter Erases Previously Selected Options

When using the Knockout-Kendo MultiSelect control, I have encountered an issue. If I select a value from the list, then enter a second value and press enter, the previously entered values are removed. VIEW <select data-bind="kendoMultiSelect: { da ...

When dynamically adding an option, the select value becomes empty

I am facing a problem with a select element that I cannot change programmatically. Initially, the select has only one option: The initial HTML structure looks like this: <select id="clients" name="client"> <option>Existing Clients...</ ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Can you explain the purpose and functions of buildOptions and preserveCompilationContext?

Exploring the recently released ASP.NET Core, I have initialized a new project and am currently examining the project.json file. Can someone explain the purpose of this configuration section? "buildOptions": { "emitEntryPoint": true, "preserveComp ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

I am unable to retrieve the class within the same namespace

Currently, I am facing an issue where I am unable to access the instance of a class within the same namespace. namespace WebProj.Controller { public class DataLayer { public string ConnString { get; set; } } } namespace WebProj.Contro ...

The VueJS application's Vuex Getter appears to display as an empty array, yet when utilizing console.log, it reveals itself as an object containing all the corresponding values

Here's the method I'm using, it's pretty straightforward. DailyCountTest: function (){ this.$store.dispatch("DailyCountAction") let NewPatientTest = this.$store.getters.NewPatientCountGET console.log(NewPatientTest) } The getter ret ...

What is the process for subtracting data from an object in a Node.JS environment?

My task involves analyzing sensor data which is stored as an array of objects containing current and previous month's information. The goal is to calculate the difference between the current and previous month's data and add this difference to th ...

Navigating through a website that loads content dynamically with AJAX can be easily done by

Having an issue with scraping data from a website using jQuery AJAX. There are 300 links to scrape, but the site only shows 50 at a time, requiring scrolling to load more. Can someone assist me with this? var baseURL = "https://hr.myu.umn.edu/psc/hrp ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

Disable or eliminate the event listener

Working on my Angular2 application, I've set up an RxJS timer that sends notifications to users when they are logged in. The twist is, the notification should only be sent if the tab is active; otherwise, the scheduler should pause or stop. I have man ...

Choose a particular element within an element class using a variable as the selector in jQuery

Is there a way to dynamically add a class to a specific element in an array based on a variable in a for loop, rather than random selection? I need to target elements with the variable provided and possibly apply the class to more than one element if neces ...