Home > Net >  POST request getting null value of string on Angular with C# API
POST request getting null value of string on Angular with C# API

Time:12-19

I am trying to call a simple request, but the value(property) in API is null. Do you have any suggestions?

C#

[Route("getpagefields")]
[AcceptVerbs(WebRequestMethods.Http.Post)]
public IHttpActionResult GetPageFields([FromBody]string property)
{
   USERS user = TokenUtils.Authonticate(Request);
                
   return Ok(new { fields = WebServiceBL.GetPageFields(property) });
}

.ts

GetPageFields(){
  debugger;
  let urlPart = this.router.url.split('/')[3];
  let params = new HttpParams();
  params = params.set('data', urlPart);
  let test = this._httpClient.post(environment.apiBaseUrl 'users/getpagefields',params).subscribe(() => {   
 });
}

Example Screenshot

CodePudding user response:

3 Ways of submitting Data via POST-Request in Angular

You can either submit your data via request-body, via query-params or via request-header. I made one example for each of these possibilities:


Submitting Data via Request-Body:

If you want to submit data via body, you can wrap it in an object and pass it via the second parameter:

const myData = { id: '1', name: 'Lukas' };
this.http.post(url, myData).subscribe();

And your .Net backend-method will then expect and object that corresponds to myData:

[HttpPost]
public IHttpActionResult GetPageFields([FromBody]MyDataObject myObject)
{
   var id = myObject.id;
   var name = myObject.name;
}

Submitting Data via Query-Params:

If you want to pass string values via HttpParams, they need to be passed as a property of third argument:

const params = new HttpParams()
                    .set('id', '1')
                    .set('name', 'Lukas');

this.http.post(url, null, { params });

And the corresponding .Net backend-method might look like this:

[HttpPost]
public IHttpActionResult GetPageFields([FromQuery] string id, [FromQuery] string name)
{
   var id = id;
   var name = name;
}

Submitting Data via Request-Header

In Angular you can submit data via Http-Header like this:

const httpHeaders = new HttpHeaders()
                    .set('id', '1')
                    .set('name', 'Lukas');    

const options = { headers: httpHeaders };

this.http.post(url, null, options);

And the corresponding .Net backend-method might look like this:

[HttpPost]
public IHttpActionResult GetPageFields()
{
    var id = Request.Headers.FirstOrDefault(x => x.Key == "id").Value.FirstOrDefault();
    var name = Request.Headers.FirstOrDefault(x => x.Key == "name").Value.FirstOrDefault();
}
  • Related