Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting to ASP.NET WebApi server from AngularJS client

I'm trying to post strings from an AngularJS application (using $http) to a server built on ASP.NET WebApi, but I get 404 as soon as I add a parameter.

The client code is this

$scope.add = function () {
    // ...cut...
    $http({ method: "POST", url: url, data: { fileString: "test string" }}).then(
        function successCallback(response) {
            $log.info(response.data);
        }
    );
}

The server code is

[HttpPost]
public IHttpActionResult UploadExcel(string fileString) {
    // cut
}

I get a 404, but if I remove the parameter on server side it works, so i can use a server side code like this

[HttpPost]
public IHttpActionResult UploadExcel() {
    // cut
}

What is wrong? Should I pass the data in a different way? I tried different combination but I can't get it work.

like image 831
Naigel Avatar asked Jan 06 '23 20:01

Naigel


2 Answers

What you want to do is send a string, not a JSON object as you are doing right now with { fileString: "test string" }. When I want to send a string, what I normally do is that I send data from Angular like this:

$http.post("/Search/QuickSearch?searchQuery="+ searchString);

And my controller I make ready to receive a string like this:

[HttpPost]
public IHttpActionResult QuickSearch(string searchQuery)
{
    // cut
}

If I want to send a JSON object, I tell my controller what it should expect, like this:

[HttpPost]
public IHttpActionResult SaveActivity(ActivityEditForm form);
{
    // cut
}

public class ActivityEditForm
{
    public int? Id { get; set; }
    [Required]
    public string Title { get; set; }

    public string Description { get; set; }
}

And then send my JSON from Angular like this:

$http.post("/Activity/SaveActivity", { form: activity });
like image 60
Squazz Avatar answered Jan 19 '23 08:01

Squazz


I suggest you should capture the request send by Angular. By default, Angular send parameters in a json string in request body.

I'm not sure wether Asp.net can parse them from json string in body.

So, you can try to add the below codes (also need jQuery)

angular.module('yourApp').config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});
like image 24
Eric Zeng Avatar answered Jan 19 '23 07:01

Eric Zeng