Angular 11 and .Net post method not working - c#

I am trying to post data from Angular side to .Net and I'm not hits the breakpoint at Controller c#.
Do I need some configuration? I have already sent data in this way in Angular 8 before and it was working.
c#
public class UpdateViewModel
{
public int Id { get; set; }
public string Title { get; set; }
}
[HttpPost]
[Route("delete")]
public void delete(UpdateViewModel model)
{
//return Ok();
}
ts
var model = {
Id: 1,
Title: 'test'
}
return this.http.post(this.baseURL + "home/delete/", model)
.pipe(
retry(1),
catchError(this.errorHandler)
);

the http client of angular is based on observables. This means, the request will only be sent if you subscribe to the observable. You can do this with .subscribe()or with .toPromise().
For your code:
return this.http.post(this.baseURL + "home/delete/", model)
.pipe(
retry(1),
)
.subscribe({
error: this.errorHandler
});

Related

Angular posting FormData to .Net Core webAPI are always null

I have a file uploader component in angular that posts a file and a json object string to a web api controller. unfortunately the values on the server are always null.
Here is the angular method used for upload :
public upload(event: any): void {
const file = event.target.files[0];
const formData = new FormData();
var product = {
productCode: '009',
productName: 'Test Product Name',
clientKey: '616f1d97-6798-459a-957f-6e6476aa3c82',
providerId: 1
};
formData.append('file', file, file.name);
formData.append('body', JSON.stringify(product));
var headers = { headers:{
'Content-Type': 'application/json',
'TimeStamp' : '2022-05-05T16:50:36'
}}
this.http.post('http://localhost:9913/api/internal/testProduct/Add', formData, headers)
.pipe(
map(res => console.log('got response', res),
catchError(error => of(console.error('got error', error)))))
.subscribe(() => console.log('next'), error => console.log(error));
}
And the web api controller method:
[HttpPost("Add")]
public async Task<IActionResult> AddProduct([FromForm] AddProductEntity addProductEntity)
{
ProductRequestContract addNewProductRequestContract = new ProductRequestContract();
var requestObj = JsonConvert.DeserializeObject<ProductRequestContract>(addProductEntity.body);
if (requestObj == null)
{
return base.BadRequest("Not valid product");
}
#region upload file to temp folder
if (addProductEntity.file != null)
{
var uploadFileResult = SaveImage(addProductEntity.file);
if (!uploadFileResult)
{
return BadRequest("Error saving the file.");
}
}
#endregion
return Ok();
}
the parameter AddProductEntity addProductEntity are always null, why web api model binder is unable to match form data sent in the request?
Note: AddProductEntity is a simple DTO class has 2 props which matches the form data values:
public class AddProductEntity
{
public IFormFile file { get; set; }
public string body { get; set; }
}

MVC5 WebApi 2 create not getting value from body ([FromBody])

I created a simple create Web API 2 action that will get an object from the post body and then will set it to the DAL layer. However no matter what I do using postman to get the object into the method, it always stays null.
The model looks like this:
namespace WebApi.Models
{
using System;
using System.Collections.Generic;
public partial class Classes
{
public int Id { get; set; }
public string ClassName { get; set; }
public int MaxStudents { get; set; }
}
}
My controller is as follows:
[HttpPost]
public IHttpActionResult CreateClass([FromBody] Classes classObj)
{
if (classObj == null)
{
return BadRequest("missing parameters.");
}
var newClass = new Classes()
{
ClassName = classObj.ClassName,
MaxStudents = classObj.MaxStudents
};
_context.Classes.Add(newClass);
_context.SaveChanges();
var newClassUrl = Url.Content("~/") + "/api/classes/";
return Created(newClassUrl, newClass);
}
Now when I use postman I tried two options.
option 1:
URL: http://localhost:53308/api/classes/
Headers: Content-Type: applications/json
[
"classObj": {
ClassName = "test"
MaxStudents = 100
}
]
option 2:
URL: http://localhost:53308/api/classes/
Headers: Content-Type: applications/json
ClassName = "test"
MaxStudents = 100
but in both cases classObj stays empty and it returns "missing parameters.". So obviously I'am missing something here.
What am I doing wrong?
Your payloads do not match the expectation of the action.
For example
[HttpPost]
public IHttpActionResult CreateClass([FromBody] Classes classObj) {
//...
}
Would expect JSON data that looks like this
{
"ClassName": "test"
"MaxStudents": 100
}
Also given that the model posted into the action is the same type added to the store there isn't really a need to create a new instance.
[HttpPost]
public IHttpActionResult CreateClass([FromBody] Classes classObj) {
if (classObj == null) {
return BadRequest("missing parameters.");
}
_context.Classes.Add(classObj);
_context.SaveChanges();
var newClassUrl = Url.Content("~/") + "/api/classes/" + classObj.Id.ToSTring();
return Created(newClassUrl, classObj);
}

Posting to asp.net core mvc app results in null body and null input parameter

This is my first asp.net core app, so I'm probably missing something obvious, but I've looked through the other StackOverflow answers, and the solutions there haven't helped me. I have an asp.net core mvc app that I'm running on service fabric, and I'm trying to post a string to a controller. The string is originally an array of json objects.
My ajax post:
var sendThis = { "operations": JSON.stringify(operations) };
$.ajax({
url: '/Home/Execute',
type: 'POST',
data: sendThis,
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
$("#save-footer-text").val("Saving failed. Please contact an administrator");
},
success: function (result) {
$(".save-footer").addClass("slider");
},
async: true
});
My controller on the other side. I took the stream stuff from another stack overflow answer, but it just returns an empty string when it's done.
[HttpPost]
public IActionResult Execute([FromBody] string operations /*this is null*/)
{
var i = 5;
string documentContents; //this will be an empty string.
Request.Body.Position = 0;
using (Stream receiveStream = Request.Body)
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.Unicode))
{
documentContents = readStream.ReadToEnd();
}
}
Console.WriteLine(i);
return new OkResult();
}
From the other stackoverflow answers, I've also tried posting with traditional set to to true, and I've tried posting operations into a model, like this
public class M
{
public string status { get; set; }
public string appName { get; set; }
public string startTime { get; set; }
public string endTime { get; set; }
public string description { get; set; }
public string operation { get; set; }
}
with the controller changed to public IActionResult Execute([FromBody] List<M> operations)
I've checked that my javascript does send a request, with Chrome tools reporting that the Request payload is:
operations= my json string here
I also see this in Fiddler, so I know it is going over the wire.
Per this answer, I've also tried updating JsonSettings, but that didn't help either.
I'm using 1.0.0-rc2-final for the asp.net core package, and 5.1.150 for service fabric.
What am I missing here? Sorry if the answer is really trivial. Thank you for any help.
If the operations variable in the script is an array
var operations = new Array();
var op1 = { status: 's1', appName: 'a1', startTime: 'st1', endTime: 'e1', description: 'd1', operation: 'o1' };
operations.push(op1);
var op2 = { status: 's2', appName: 'a2', startTime: 'st2', endTime: 'e2', description: 'd21', operation: 'o2' };
operations.push(op2);
var sendThis = JSON.stringify(operations);
...// ajax call here
And the controller post method is defined as follows then List<M> operations should contain the values sent over the wire as expected.
[HttpPost]
public IActionResult Execute([FromBody]List<M> operations)
{
// ... some code here
return Json("");
}
It is a list of M?
If it is, then your json shouldn't be like this
var sendThis = { "operations": JSON.stringify(operations) };
try this:
var sendThis = JSON.stringify(operations);
I think asp.net is trying to deserialize an object like this one:
public class Operation
{
public List<M> Operations { get; set; }
}

Passing 3 parameters from angularjs $resource to C# Web API Controller Post method, one of the parameters returns null

I have been trying to pass 3 parameters into my post method from angularjs to my C# web api controller. The information is being passed to the angularjs service correctly. But Have tried many combinations on the client and server side post method to receive multiple parameters but the closest I have come is 2/3.
here is my code.
SERVER SIDE CONTROLLER:
// POST api/values
[HttpPost("{id}")]
public IActionResult Post(int id, string userId, [FromBody]Post post)
{
if(post.Id == 0)
{
_repo.AddPost(id, userId, post);
}
else
{
_repo.UpdatePost(post);
}
return Ok(post);
}
CLIENT SIDE SERVICE:
namespace MyApp.Services {
export class PostsService {
private postsResource;
constructor(private $resource: ng.resource.IResourceService) {
this.postsResource = this.$resource("/api/posts/:id");
}
getPost(id) {
return this.postsResource.get({ id: id });
}
savePost(id, userId, postToSave) {
return this.postsResource.save({ id: id }, { userId: userId }, postToSave).$promise;
}
deletePost(id) {
return this.postsResource.delete({ id: id }).$promise;
}
}
angular.module("MyApp").service("postsService", PostsService);
}
Any tips or suggestions? Much appreciated!

AngularJS $http.post() sends null to ASP.NET web API controller method

I'm trying to submit a form from angularjs controller as $http.post() to asp.net web api method. But it sends null value. Here is my code
//angular controller
$scope.newpost = {};
$scope.save = function () {
console.log($scope.newpost); // it logs data accurately
$http.post('/api/NewPost', $scope.newpost).
success(function (data, status, headers, config) {
alert("ok");
});
}
//api
public HttpResponseMessage post(NewPost newpost) //fields are null here. I tried [FromBody] $ [FromURI], but no luck
{
posts.Add(newpost);
String id = newpost.Id; //saving is ok.
return Request.CreateResponse(HttpStatusCode.OK);
}
//model
public class NewPost
{
public String Title { get; set; }
public String Content { get; set; }
public String Tags { get; set; }
}
console.log($scope.newpost) displays-
Object {Title: "t", Content: "tt", Tags: "ttt"}
Any help?
use this:
console.log($scope.newpost.Title ); // it should logs data accurately
console.log($scope.newpost.Content );// it should logs data accurately
console.log($scope.newpost.Tags );// it should logs data accurately
$http.post('/api/NewPost', $scope.newpost).
success(function (data, status, headers, config) {
alert("ok");
});

Categories

Resources