Tips for accessing HttpParams within a WebApi Controller while utilizing the [HttpPut] method

I am attempting to update a specific resource by accessing it through the PUT method in an Angular service.

RollBackBatchById(selectedBatchId: number) {
    const params = new HttpParams();
    params.append('resourceId', resourceId.toString());
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    const httpOptions = { headers: headers };
    return this._httpClient.put(this.base_url + 'api/WebApi/UpdateResource', { params: params })
      .subscribe((res: Response) => {

      });
  }

Within my WebApi Controller:

[HttpPut]
[Route("UpdateResource")]
public TransactionResult UpdateResource([FromQuery]string resourceId)
{
    var id = resourceId;
}

However, I am encountering an issue where the resourceId is arriving as null when accessed and checking the network activity does not show the resourceId appended to the URL.

If anyone could offer assistance with solving this problem, I would greatly appreciate it.

Answer №1

After conducting some research on HttpParams, I discovered that they are immutable.

If you're interested in learning more about HttpParams, check out this helpful link: Angular 4.3 - HttpClient set params

This is the solution:

RollBackBatchById(selectedBatchId: number) {
    const params = new HttpParams().append('resourceId', resourceId.toString()); 
    //chaining the parameters
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    const httpOptions = { headers: headers };
    return this._httpClient.put(this.base_url + 'api/WebApi/UpdateResource',null { params: params })
      .subscribe((res: Response) => {

      });
  } 
  1. PUT expects a body as the second parameter which I am not sending. So changed it to NULL.
  2. HttpParams are immutable, so they always return a new instance of HttpParam, which will be null. That's why I switched to chaining.

As a result, my URL construction has now become:

api/WebApi/UpdateResource?resourceId=XXX

Answer №2

I believe there might be an issue with how you are defining the REST URL for the PUT method in your code. To address this, I recommend updating the URL to: 'api/WebApi/UpdateResource/id'

Here is an example of how the C# Controller should look:

[HttpPut]
[Route("UpdateResource/{resourceId:int}")]
public TransactionResult UpdateResource([FromUri]int resourceId)
{
    var id = resourceId;
}

In this snippet, I used int as the data type for "resourceId". For more available types, refer to this link: https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Next, let's take a look at the Angular code:

RollBackBatchById(selectedBatchId: number) {
    const params = new HttpParams();
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    const httpOptions = { headers: headers };
    return this._httpClient.put(`${this.base_url}api/WebApi/UpdateResource/${selectedBatchId}`, null, { params: params })
      .subscribe((res: Response) => {

   });
} 

Please give it a try and let me know if this adjustment resolves the issue. Best of luck.

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 trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

The creation of a fresh child instance in Typescript using rest parameters

My goal is to create a parent class that allows children to generate new instances of the same child type. When I specify the number of parameters, everything functions correctly: abstract class AClass { protected sameTypeWithSingle ( x: any ): t ...

The React table column definition inexplicably transforms into a string

When working with react-table in Typescript, I encountered an issue while defining the type for my columns within a custom hook. It seems that when importing the hook and passing the columns to my Table component, they are being interpreted as strings inst ...

What could be causing the 404 error when trying to make a get-request to fetch a list of all users?

Having trouble retrieving a list of users using my endpoint, as it keeps returning a 404 error. I have set up a model, controller, router, and index file for the user in my application. Below is the User.ts model: import { Schema } from 'mongoose&apo ...

Execute Internet Explorer as a distinct user through Selenium

Is it possible to launch a single instance of Internet Explorer with Selenium as a different user? I came across a post on this topic, but I'm still struggling to make it work. How can I run Internet Explorer Selenium tests as a specific domain user? ...

Dynamic placeholder modification depending on form selection

How can I dynamically change the placeholder text based on user selection? //div with a toggle for two options <div fd-form-item> <label fd-form-label for="select-targetType">Showroom type:</label> <select class=&q ...

Running Jenkins in a Docker container to initiate the process of building an Angular application within a

Recently, I began my journey of learning Jenkins and successfully launched it on Docker. Now, I have a project built in Angular along with a Dockerfile created to produce a Docker image. However, when attempting to start the process from Jenkins, an erro ...

Error: Report viewer tag not found in Visual Studio 2015 toolbox

After installing Visual Studio 2015 Community, I noticed that the report viewer tag is missing from my toolbox. Additionally, all existing report viewers in my ASP.NET project display an 'error creating Control' message. Despite checking all of m ...

What is the method for showing the number of characters in a string within a textfield by utilizing events in Angular

I have been working on a project that requires me to calculate and display the length of a string entered into a text field using Events. There is an additional condition where the string length must be greater than 4 in order for the length to be displaye ...

Choosing the primary camera on a web application with multiple rear cameras using WebRTC

Having a bit of trouble developing a web app that can capture images from the browser's back camera. The challenge lies in identifying which camera is the main one in a multi-camera setup. The issue we're running into is that each manufacturer u ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Assistance needed: How to add extra information when registering a user on JHipster?

After diligently following this tutorial to add more information about the user, I encountered an issue while trying to include an input field in the register.component.html. As soon as I added the ngModel directive, the page stopped functioning properly. ...

Retrieving the component's values when utilizing the `<ng-content>` directive

Seeking a technique for accessing the values of a component when utilizing <ng-content>: import {Component} from '@angular/core'; @Component({ selector: 'home-page', template: `<person-box>{{name}}</person-box> & ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

Elevate a counter value within a nested for loop in Angular framework

I need to update a count within a nested loop and display the value (e.g. 1,2,3,4) when the table loads. The challenge is that my objects have varying lengths, so with 100 rows in the table, the counter column should display numbers from 1 to 100. <ng- ...

Ensure that the background view remains interactive while adding an overlay on top for an enhanced user experience

Hey everyone, I could use some help with a question I have. My issue is that I am struggling to figure out how to make two views overlap while still allowing the background view to be interactive. Currently, I am using absolute positioning for the foregr ...

Encountering TypeScript error TS2339 while mocking a React component with Jest

When attempting to mock a React component using Jest, I encountered an issue where TypeScript was not recognizing the mocked methods and showing a TS2339 error. Below is the test code snippet causing the problem: jest.mock('./features/News/News' ...

Prevent user input when an alert window is open

Users keep pressing the enter key multiple times when an alert box pops up, causing them to accidentally dismiss the message by hitting 'ok'. Is there a simple way to prevent key presses on alert windows and only allow mouse input? ...