c# - 从 Angular 发送到 c# api 失败

标签 c# angular api

我正在发送到 c# api。其中一个功能未发送到 api。 你能告诉我是什么原因吗? (此 api 的其他功能运行良好)。

组件。

    this.loggedUser.aValidateUser(this.newlyRegistered.uMobile).subscribe(res => {
      alert("personal details were saved successfully"),
        this.active = 2;
    }, err => {
      alert("There were wrong details. Please make the necessary changes");
    }
    );
  }

Angular 服务:

  aValidateUser(phoneNumber:string) {
    return this.HTTP.post('http://localhost:54058/user/ValidateUser', phoneNumber ,this.httpOptions);
  }

C# 接口(interface):

  [EnableCors("*", "*", "*")]
    [RoutePrefix("user")]
    public class UserController : ApiController
    {
        SenderLogic user = new SenderLogic();

        [HttpPost]
        [Route("UploadFile")]
        public void UploadFile()//Saves passport in local folder
        {
            for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
            {


                var file = HttpContext.Current.Request.Files[i];
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + Path.GetFileName(file.FileName);
                    var path = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), fileName);
                    file.SaveAs(path);
                }
            }
        }

        [Route("ValidateUser")]
        [HttpPost]  
        public bool ValidateUser(string phoneNumber)//check if phone number-(identifier of user) exists
        {      
            if (user.ValidateUser(phoneNumber) == true)
                return true;
            return false;
        }

调试显示服务没有发送到 c# api。而具有相同 api 和函数类型的其他函数运行良好。

编辑 确实有效的功能: Angular -

  if (files.length === 0) {
    return;
  }
  let filesToUpload : File[] = files;
  const formData = new FormData();
  Array.from(filesToUpload).map((file, index) => {
    return formData.append('file'+index, file, file.name);
  });
  this.clientHttp.post('http://localhost:54058/user/UploadFile', formData, {reportProgress: true, observe: 'events'})
    .subscribe(event => {
      if (event.type === HttpEventType.UploadProgress)
        this.progress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response) {
        this.message = 'Upload success.';
      }
    });
}

C# 接口(interface):

 [HttpPost]
        [Route("UploadFile")]
        public void UploadFile()//Saves passport in local folder
        {
            for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
            {

                var file = HttpContext.Current.Request.Files[i];
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + 
                  Path.GetFileName(file.FileName);
                    var path = 
       Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), 
      fileName);
                    file.SaveAs(path);
                }
            }
        }

最佳答案

希望对您有所帮助的两件事。

  1. 尝试更改

    的签名
    public bool ValidateUser(string phoneNumber)
    

    public bool ValidateUser([FromBody] string phoneNumber)
    
  2. Angular 变化:

    return this.HTTP.post('http://localhost:54058/user/ValidateUser', phoneNumber ,this.httpOptions);
    

    return this.HTTP.post('http://localhost:54058/user/ValidateUser', JSON.stringify(phoneNumber) ,this.httpOptions);
    

通常避免将基本类型(int、string 等)传递给 POST 方法。例如,将它们包装在模型类中

public class UserPhone {
   public string Phone {get; set;}
}

Controller 方法应该这样改变:

public bool ValidateUser([FromBody] UserPhone phoneNumber)

和 Angular 方法:

return this.HTTP.post('http://localhost:54058/user/ValidateUser', {phone: phoneNumber} ,this.httpOptions);

关于c# - 从 Angular 发送到 c# api 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021461/

相关文章:

c# - 在另一个线程中使用线程时发生内存泄漏

Angular-cli Karma 测试不适用于新项目

asp.net - Angular 2 与 RequireJS 导入错误

python - Kubernetes Python API 客户端 : execute full yaml file

node.js - 如何从 Rally API 获取相关对象

c# - 将 excel 工作簿转换为 byte[]

C#在不同的线程中接收键盘钩子(Hook)回调

c# - 如何在 C# String 和 C Char 指针之间进行转换

javascript - next() 不通知 subscribe()

android - Unity Ads 4.0 - 奖励广告的多个 OnUnityAdsShowComplete 回调