【问题标题】:Unable to pass array of integers to asp.net webapi from angular 7 application无法从 Angular 7 应用程序将整数数组传递给 asp.net webapi
【发布时间】:2019-07-08 19:34:19
【问题描述】:

我正在尝试通过我的 Angular 7 应用程序 getDocumentUploadDetailsByIds 方法将整数值数组传递给服务器 webapi 端点。由于某种原因,端点正在接收空值。我尝试了几种方法,但端点的参数为空。谁能告诉我哪里出错了

组件

  export interface IDocumentIds {
    ids: number[];
    }

          documentIds: IDocumentIds = <IDocumentIds>{};


          this.documentUploadService.createDocumentUpload(this.documents)
                    .then((result) => {
                        if (result) {
                            this.documentIds.ids = Object.keys(result).map(k => result[k]);
                            console.log(this.documentIds);
                            this.getDocumentUploadDetailsByIds(this.documentIds);
                            this.setGridOptions();
                            this.setColumns();
                            this.notify.success('Documents uploaded Successfully');
                        }
                    }).catch(err => {
                        this.notify.error('An Error Has Occured While uploading the documents');
                    });

 public getDocumentUploadDetailsByIds(documentIds) {
        if (this.ManagerStrategyId != null) {
            this.Loading = true;

            this.initGrid();
            this.documentUploadService.getDocumentUploadDetailsByIds(documentIds)
            .then((data) => {
                if (data) {
                    this.DocumentUploadDetails = data;
                    this.Loading = false;
                    this.notify.success('Documents uploaded Successfully');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While uploading the documents');
            });
        }
    }

服务

     getDocumentUploadDetailsByIds(documentIds: IDocumentIds) {
                    return this.mgr360CommonService.httpGetByKey('/api/documentupload/detailsByIds' ,  documentIds);
                  }      

const httpPostOptions = {

    headers:
        new HttpHeaders(
            {
                'Content-Type': 'application/json; charset=utf-8',
            }),

    withCredentials: true,
};

        httpGetByKey(url: string, key: any) {

            return this.httpClient.get(this.webApiLocation + url + '/' + key, httpPostOptions)
                .pipe(map((response: Response) => {
                    return response;
                }))
                .toPromise()
                .catch((error: any) => {
                    this.onError(error);
                    return Promise.reject(error);
                });
        }

asp.net web api 型号

  public class DocumentIdViewModel
    {
       public int[] ids;
    }

端点

 [HttpGet]
            [Route("api/documentupload/detailsByIds/{id}")]
            public IHttpActionResult DetailsByIds(DocumentIdViewModel documentIds)
            {
                var viewModel = GetDocumentUploadDetailsByIds(documentIds);
                return Ok(viewModel);
            }

我也试过将参数设置为web方法的int数组

从角度

this.getDocumentUploadDetailsByIds(this.documentIds.ids);

在服务器上

 public IHttpActionResult DetailsByIds(int[] documentIds)
        {
            var viewModel = GetDocumentUploadDetailsByIds(documentIds);
            return Ok(viewModel);
        }

【问题讨论】:

标签: angular asp.net-web-api


【解决方案1】:

如果您在正文中传递ids,则添加[FromBody]

[HttpPost]
public IHttpActionResult DetailsByIds([FromBody] int[] documentIds)
{
}

否则,如果您在 URI 中发送您的 ID:

[HttpPost]
public IHttpActionResult DetailsByIds([FromUri] int[] documentIds)
{
}

更新: 为了获取枚举参数,您应该创建以下查询字符串:

localhost:56888/api/documentupload/DetailsByIds?
    detailsByIds=123&detailsByIds124&detailsByIds125 

在 MSDN Parameter Binding in ASP.NET Web API 上有一篇很棒的关于参数的文章

您可以使用HttpParams 类来创建参数。由于您的参数名称相同,因此您可以创建一个循环。这是一种将 URL 参数传递给 HTTP 请求的方法:

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

Angular docs about passing parameters to HTTP requst.

更新 1:

让我举例说明如何添加参数:

const array = [1, 2, 3, 4, 5];
let params = new HttpParams();
array.forEach(id => {
  params.append('detailsByIds', id);
});

【讨论】:

  • 我尝试了 [FromUri] int[] documentIds 和 [FromBody] int[] documentIds 都没有工作
  • 如何创建枚举参数?
  • 我不应该在角边创建那个
  • 在您共享的示例中,它显示了固定参数。就我而言,它可能是几个值。如果我要传递一个对象,那么它应该只有一个参数对
  • @Tom ,请查看我的更新答案。如果您觉得我的回复对您有帮助,您可以将其标记为答案。 meta.stackexchange.com/questions/5234/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2016-10-06
  • 2012-04-16
  • 1970-01-01
相关资源
最近更新 更多