Using TypeScript with C# WebApi for POST Requests

I am encountering an issue where I am trying to invoke a simple method using TypeScript code as well as Chrome Advanced Rest Client, but I keep receiving a 404 error.

WebApi Method

[HttpPost]
[Route("api/offert/TestPost")]
public IHttpActionResult TestPost(int idid)
{
    //http://localhost/prova/api/offert/TestPost

    var anonymousTypeVar = new { x = 15, y = 120 };
    return Json(anonymousTypeVar);
}

TypeScript Code

var data = { idid: 1};

this.baseUrl = 'http://localhost/prova/api/offert/';
this.http.post(this.baseUrl + "TestPost", JSON.stringify(data), 
this.getRequestOptions)
      .map(response => response.json())
      .subscribe();

Despite my efforts, the 404 error persists...

I am aware that I could append "?idid=1" to the URL as a parameter, but my intention is to pass a Json string to the webmethod...

What changes should I make in the code?

Thank you

Answer №1

Could it be that the issue lies in your JSON data? It seems like MVC would easily handle mapping a URL or Body containing key value pairs to a simple parameter, such as:

id=1 -> int id

However, you are passing:

{ id: 1 }

This should be mapped to...

public class OffertRequest
{
    public int id { get; set; }
}

Therefore, your API should look like:

public IHttpActionResult TestPost(OffertRequest id)

Alternatively, consider sending a straightforward key/value pair in the request body.

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

When you subscribe to a forkJoin, you will receive an error notification

Trying to determine when all my observables have returned their values is a challenge I'm facing. Here's my approach after including import { Observable } from 'rxjs/Rx';: let observables:any[] = []; observables.push(this.getV ...

Utilizing typescript to isolate specific functionality from a class without extending it

Imagine a scenario where I have a class with different areas of functionality: export class TreeTable extends someOtherClass { constructor(){ super.constructor(); } //========= area 1 of functionality ==== itemRightClick(){this.contex ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

React with Typescript: Potential occurrence of an undefined object

While working with React and TypeScript, I encountered the error Object is possibly 'undefined' when using language.toLowerCase().includes(selectedCategory). To address this issue, I implemented a check as shown below. Although this resolved th ...

Base URL for making Http Requests in an Angular application

I am currently working on an angular application that is hosted on a test server running IIS with a .net core backend. The application is set up on a virtual directory, for example www.myTestApp/crm (the actual domain name being fictional). During the buil ...

Update to Material-UI 4.8.1 - Is there a different method for defining the `component` property now?

Note: Please note that there was a bug in version 4.8.x which caused this issue. To resolve it, make sure to upgrade to version 4.9.0 or above. In the initial version 4.8.0, the following code would compile and run smoothly: <DialogContent> {/* us ...

Challenge with sharing an array from a different component in Angular using @Input()

Recently, I started learning Angular and decided to create a basic blog application. While trying to retrieve a property from another component using the @Input() decorator, I encountered an issue specifically related to arrays. In a post-list-item compone ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

Unable to perform type casting in Typescript

I recently dived into the world of TypeScript by picking up a book titled Typescript Revealed (Published in February 2013). Chapter 2 caught my attention with a section on "Casts" featuring an intriguing example: var a : int = <int>SomeNumberAsAStri ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

What is the best way to depict object key replacements within a Typescript definition?

I currently have these types: type PossibleKeys = number | string | symbol; type ValueOf<T extends object> = T[keyof T]; type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>> = ...

Node.js built-ins require shims, while global variable names are absent

After updating my project using npm-check-updates, I encountered a strange error that stumped me. Despite following the suggested terminal command to install polyfill-node, the issue persisted with no resolution in sight online. The error displayed on the ...

Retrieve the delimiters used by the database provider from a given regular expression

Currently, I have established a connection using ADO.Net and am in the process of retrieving datasource information from various providers such as SQL Server, Oracle, MySQL, ODBC, etc. Upon executing the following code: DataTable collection = connection. ...

Transferring the date from an HTML input to a TypeScript file in Angular when the button

On my HTML page, I have two input fields for dates that need to be passed to the backend along with other parameters when a button is clicked. Here is the current setup: <input [owlDateTime]="dt1" placeholder="From a date" [value]="dateFrom.value"& ...

Arrange the DataTable by the date column in the format (dd MMM yyyy)

I'm looking to organize the data in my dataset called ds by sorting the datatabel according to a specific column named Date. The values in this column are formatted as 'dd MMM yyyy'. ...

Generate md-card components in real-time using data fetched from an API

I have a scenario where I make an API call to fetch user profiles, and I want to generate Angular Material Design md-cards dynamically for each profile. The number of profiles retrieved can vary, hence the need for dynamic card creation. Below is the comp ...

Tips for Validating an MVC Controller with Admin Authentication within IdentityServer v4

I have successfully set up my IdentityServer project to handle various grant types without any issues. However, I am now looking to create a dashboard that will allow me to efficiently manage the Identity Server. This dashboard will be hosted on the same s ...

The method for extracting values from a PXselectorgetQuery- has multiple benefits

Greetings, I am new to Acumatica development and have a question regarding retrieving data from pxselector when a row is selected. Below is the selector that I have created: https://i.sstatic.net/PTifH.png Currently, when I select a row, I am only able ...

Implementing Angular 2 reactive forms checkbox validation in an Ionic application

I have implemented Angular Forms to create a basic form with fields for email, password, and a checkbox for Terms&Conditions in my Ionic application. Here is the HTML code: <form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...