Sending to an ASP.NET WebApi server from an AngularJS client

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

Client code is

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

Server code

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

I get 404, but if I remove the parameter on the server side, it will work, so I can use server side code like this

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

What's wrong? Should I transfer data differently? I tried a different combination, but I can't get it to work.

+4
source share
3 answers

, , , JSON, { fileString: "test string" }. , , Angular :

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

​​:

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

JSON, , , :

[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; }
}

JSON Angular :

$http.post("/Activity/SaveActivity", { form: activity });
+5

Angular. Angular json .

, Asp.net json- .

, ( jQuery)

angular.module('yourApp').config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});
+2

, [FromBody] .

public IHttpActionResult UploadExcel([FromBody]string fileString)

data ,

$http({ method: "POST", url: url, data: "test string" }).then(

, , , .


@Squazz SO. webapi, .

// new class with a single string
public class InputData {
    public string fileString { get; set; }
}

// new controller 
[HttpPost]
public IHttpActionResult UploadExcel([FromBody] InputData myInput) {
    string fileString = myInput.fileString;
    // cut
}

, JSON .

$scope.add angular , ,

$scope.testDelete = function () {
    var url = "http://localhost/yourAppLink/yourControllerName/UploadExcel";
    var data = ({ fileString: "yourStringHere" });
    $http({ method: "POST", url: url, data: data }).then(
        function successCallback(response) {
            console.log("done, here is the answer: ", response.data);
        }, function errorCallback(response) {
            console.log("an error occurred");
        }
    );
}
+2

Source: https://habr.com/ru/post/1623943/


All Articles