简体   繁体   English

从AngularJS客户端发布到ASP.NET WebApi服务器

[英]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. 我正在尝试将AngularJS应用程序中的字符串(使用$http )发布到基于ASP.NET WebApi构建的服务器上,但是一旦添加参数,我就会得到404。

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 我得到一个404,但如果我删除服务器端的参数它工作,所以我可以使用像这样的服务器端代码

[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. 我尝试了不同的组合,但我无法让它发挥作用。

What you want to do is send a string, not a JSON object as you are doing right now with { fileString: "test string" } . 你想要做的是发送一个字符串,而不是像你现在正在使用{ fileString: "test string" }那样的JSON对象。 When I want to send a string, what I normally do is that I send data from Angular like this: 当我想发送一个字符串时,我通常做的是我从Angular发送数据,如下所示:

$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: 如果我想发送一个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; }
}

And then send my JSON from Angular like this: 然后从Angular发送我的JSON,如下所示:

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

I suggest you should capture the request send by Angular. 我建议您捕获Angular发送的请求。 By default, Angular send parameters in a json string in request body. 默认情况下,Angular在请求正文中的json字符串中发送参数。

I'm not sure wether Asp.net can parse them from json string in body. 我不确定Asp.net是否可以从身体中的json字符串解析它们。

So, you can try to add the below codes (also need jQuery) 所以,你可以尝试添加以下代码(也需要jQuery)

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

The first error is in the controller, [FromBody] should be used with the input parameter. 第一个错误在控制器中, [FromBody]应与输入参数一起使用。

public IHttpActionResult UploadExcel([FromBody]string fileString)

Then the data variable on the client should be a single string, so 那么客户端上的data变量应该是一个单独的字符串,所以

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

Anyway I found some issue with this solution later, it seems the simplest but I suggest to avoid it. 无论如何我后来发现这个解决方案存在一些问题,看起来最简单,但我建议避免它。


Best solution 最佳方案

Thank to @Squazz answer and this SO answer I strongly suggest a change in the webapi controller, client was correct. 感谢@Squazz的答案和这个SO答案我强烈建议改变webapi控制器,客户端是正确的。 Just introduce a class to handle a single string and adapt the input parameter 只需引入一个类来处理单个字符串并调整输入参数

// 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
}

This way JSON code from the client is automatically parsed and it's easy to change the data input. 这样就可以自动解析来自客户端的JSON代码,并且可以轻松更改数据输入。

Extra tip 额外提示

$scope.add angular function was correct as in the question, but here is a more complete example $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");
        }
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM