简体   繁体   English

从Angular将Json对象解析为C#ASP.Net Core Web API

[英]Parse Json object from Angular to C# ASP.Net Core Web API

I'm trying to create a new Salesman with Angular and C#. 我正在尝试使用Angular和C#创建一个新的推销员。 From Angular i collect the data the user has typed into an array (newData) and sending it from my controller --> service to my C# controller server-side. 我从Angular收集用户输入到数组(newData)中的数据,并将其从控制器->服务发送到我的C#控制器服务器端。 But i get several errors and it can't get my object. 但是我遇到了几个错误,但无法获取我的对象。

Angular controller: 角度控制器:

$scope.addSalesman = function (newData) {
    myService.addNewSalesman(newData).then(function (data) {
      console.log(data);
    }, function (err) {
      console.log(err);
    });
  };

Angular service: 角度服务:

addNewSalesman: function (newData) {
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: '/api/Salesman',
                headers: { 'Content-type': 'application/json' }
            }, newData).then(function (res) {
                deferred.resolve(res.data);
            }, function (res) {
                deferred.reject(res);
            });
            return deferred.promise;
        }

C# controller: C#控制器:

public HttpResponseMessage Post([FromBody] newData newdata) {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

My errors are on the C# controller: 我的错误在C#控制器上:

The type or namespace "newData" could not be found 找不到类型或名称空间“ newData”

"HttpRequest" does not contain a definition for "CreateResponse" accepting first argument of type "HttpRequest" “ HttpRequest”不包含“ CreateResponse”的定义,该定义接受“ HttpRequest”类型的第一个参数

I tried adding the using System.Net.Http; 我尝试添加使用System.Net.Http; and using System.Net; 使用System.Net; but doesn't work. 但不起作用。 Any suggestions? 有什么建议么?

You are getting two compile time errors which don't really have anything to do with one another. 您将遇到两个编译时错误,它们实际上彼此之间没有任何关系。

1. The type or namespace "newData" could not be found 1.找不到类型或名称空间“ newData”

Is caused because your parameter type "newData" is not a known type in your code. 由于参数类型“ newData”不是代码中的已知类型而导致。 Say you create a class like 假设您创建了一个类似

public class Salesman
{
    public long Id { get; set; }
    public string Name { get; set; }
}

and the javascript object is 而javascript对象是

var salesman = {
    id = 2,
    name = "Peter Sellers"
};

Now when you're passing this object in, for example by using $http.post 现在,当您传入该对象时,例如通过使用$http.post

var res = $http.post('/api/addsalesman', salesman);
res.success(function (data, status, headers, config) {
    alert(data);
});
res.error(function (data, status, headers, config) {
    alert('error');
}); 

then the following Controller method would be able to parse it. 那么下面的Controller方法将能够解析它。

[Route("/api/addsalesman")]
[HttpPost]
public IActionResult AddSalesman([FromBody] Salesman salesman)
{

}

2. "HttpRequest" does not contain a definition for "CreateResponse" accepting first argument of type "HttpRequest" 2.“ HttpRequest”不包含“ CreateResponse”的定义,该定义接受“ HttpRequest”类型的第一个参数

The method CreateResponse() doesn't exist for this.Request . 方法CreateResponse()对于this.Request不存在。 Anyways, I would suggest returning an object, which would be automatically serialized. 无论如何,我建议返回一个对象,该对象将被自动序列化。 Alternatively, you could return a not found response resulting in 404, or even throw an Exception, resulting in Statuscode 500. 或者,您可以返回未找到的响应,结果为404,甚至抛出异常,结果为Statuscode 500。

[Route("/api/addsalesman")]
[HttpPost]
public IActionResult AddSalesman([FromBody] Salesman salesman)
{
    //Do Stuff
    if (stuffNotOk)
    {
        return NotFound();
    }
    return Ok(product); 
}

It looks like you may have misspelled the name of the argument type you expect in your Post method: 看起来您可能在Post方法中拼错了所期望的参数类型的名称:

//                                         v-- this is your sinner
public HttpResponseMessage Post([FromBody] newData newdata) {
    return Request.CreateResponse(HttpStatusCode.OK);
}

The type or namespace "newData" could not be found 找不到类型或名称空间“ newData”

This means that class newData should be created which reflect data passed by UI 这意味着应该创建类newData来反映UI传递的数据

"HttpRequest" does not contain a definition for "CreateResponse" accepting first argument of type "HttpRequest" “ HttpRequest”不包含“ CreateResponse”的定义,该定义接受“ HttpRequest”类型的第一个参数

Try this 试试这个

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

相关问题 ASP.NET Core Web API如何从客户端C#发送json对象 - asp.net core web api how to send json object from client side c# 将JSON对象发布到C#ASP.NET WEB API - POST JSON object to C# ASP.NET WEB API C#从asp.net Web API返回父子JSON对象? - C# return a parent child JSON object from the asp.net web api? 如何在ASP.Net Core MVC模型中使用C#从rest api解析json数据并将其显示在HTML页面上 - how to parse json data from a rest api using C# in the ASP.Net Core MVC model and display it on a HTML page How to parse SQL JSON string in C# in asp.net mvc web api? - How to parse SQL JSON string in C# in asp.net mvc web api? 如何使用 MongoDB 将动态 JSON 属性发布到 C# ASP.Net Core Web API? - How to post a dynamic JSON property to a C# ASP.Net Core Web API using MongoDB? 使用 C# 从 ASP.NET Core MVC 中的 URL 解析 JSON 数据不起作用 - Parse JSON data from URL in ASP.NET Core MVC using C# doesn't work 使用 C# ASP.NET Core Web API 进行谷歌身份验证 - Google authentication with C# ASP.NET Core Web API C# ASP.NET Core Web API 包含与 where - C# ASP.NET Core Web API include with where 如何从控制器进行 HTTP 调用? 使用 Web API 的 Asp.Net Core C# - How to make HTTP call from Controller ? to Use web API's Asp.Net Core C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM