【问题标题】:How to do a REST API post request with FileUpload to an Azure AD Protected REST API如何使用 FileUpload 向受 Azure AD 保护的 REST API 执行 REST API 发布请求
【发布时间】:2018-12-16 10:16:41
【问题描述】:

我有以下 .net WEB API

// [Authorize]
    public class TenantController : ApiController
    {
        public async Task<List<Tenant>> GetTenants()
        {
            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            return await tenantStore.Query().Where(x => x.TenantId != null ).ToListAsync();

        }

        public async Task<IHttpActionResult> GetTenant(string tenantId)
        {
            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.TenantId == tenantId);
            if (tenant == null)
            {
                return NotFound();
            }
            return Ok(tenant);
        }

        public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant, HttpPostedFile certificateFile)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

            // Create or overwrite the "myblob" blob with contents from a local file.
            blockBlob.Properties.ContentType = certificateFile.ContentType;
            blockBlob.UploadFromStream(certificateFile.InputStream);

            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            tenant.CertificatePath = blockBlob.Uri;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != tenant.TenantId)
            {
                return BadRequest();
            }

            var added = await tenantStore.AddAsync(tenant);
            return StatusCode(HttpStatusCode.NoContent); 
        }

        public async Task<IHttpActionResult> PostTenant(string id, Tenant tenant)
        {
            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await tenantStore.UpdateAsync(tenant);
            return Ok(result);
        }

        public async Task<IHttpActionResult> DeleteTenant(string tenantId)
        {
            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            await tenantStore.RemoveByIdAsync(tenantId);// Removes an entity with the specified ID
            return Ok(tenantId);
        }
    }

我需要从 React 应用程序调用 Put Tenand 端点。

在我的 react 应用中,我已经测试了一个 GET 端点,如下所示:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: []
    };

  }

  fetchData = () => {
    adalApiFetch(fetch, "/values", {})
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  };


  componentDidMount(){
    this.fetchData();
  }

  render() {
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;
    const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px'
      };
      const plainOptions = ['Apple', 'Pear', 'Orange'];
      const options = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange' }
      ];
      const optionsWithDisabled = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange', disabled: false }
      ];

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
              <ul>
                    {data && data.map(item => (
                        <li>{item}</li>
                    ))}
                  </ul>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

我使用了这个库: https://github.com/salvoravida/react-adal

我的 adalconfig.js

import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';

export const adalConfig = {
  tenant: 'x-c220-48a2-a73f-1177fa2c098e',
  clientId: 'x-bd54-456d-8aa7-f8cab3147fd2',
  endpoints: {
    api:'x-abaa-4519-82cf-e9d022b87536'
  },
  'apiUrl': 'https://xx-app.azurewebsites.net/api',
  cacheLocation: 'localStorage'
};

export const authContext = new AuthenticationContext(adalConfig);

export const adalApiFetch = (fetch, url, options) =>
  adalFetch(authContext, adalConfig.endpoints.api, fetch, adalConfig.apiUrl+url, options);

export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints.api);

现在我需要知道在 React 中,如何将表单放入 out 元素,捕获值和最重要的值,将文件发送到端点。

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';

export default class extends Component {
  constructor(props) {
    super(props);

  }


  render(){
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;


    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
              {//Put Form here with file upload.
              }
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs typescript react-router asp.net-web-api2


    【解决方案1】:

    adalFetch 函数接受一个 fetch 对象,您可以选择使用任何 npm 包,如 fetch 或 Axios 并将其传递。从 react-adal 存储库中引用 this issue。在这里,我正在编写一个小的 sn-p 来发送带有上传进度的文件。

    import React, { Component } from "react";
    import { adalApiFetch } from "./config";
    const API_SERVER = "example.azure.com/upload";
    
    class FilUpload extends Component {
      constructor(props) {
        super(props);
      }
    
    upload(e) {
     let data = new FormData();
     //Append files to form data
        let files = e.target.files;
        for (let i = 0; i < files.length; i++) {
          data.append("files", files[i], files[i].name);
        }
    
    //add other objects or params
    data.append("myobject", { name: "Mark" });
    data.append("myobject1", { name: "Sarah" });
    
    return new Promise((resolve,reject) => {
      adalApiFetch(fetch, API_SERVER,{
          method: "post",
          headers: { "Content-Type": "multipart/form-data" },
          body: data
        })
        .then(res => res.json())
        .then(response => {
          return resolve(response);
        })
        .catch(err => {
          return reject(err);
        });
    });
    }
      render() {
        return (
          <div>
            <input multiple onChange={e => this.upload(e)} type="file" id="files" />
          </div>
        );
      }
    }
    
    export default FilUpload;
    

    对于 ASP.net 端请参考以下回答jQuery ajax upload file in asp.net mvc

    【讨论】:

    • 我需要使用 react-adal 组件,因为 api 受 azure ad 保护,但我不确定如何,他的文档真的很差。 github.com/salvoravida/react-adal
    • @LuisValencia 的概念对所有人来说都是一样的。我已经更新了答案,请尝试。
    • 我需要代码才能使用 adalapifetch,第二个。如果你看到 webapi 方法,你可以看到我有一个租户对象,这个有 2 个字符串属性,我如何发送一个对象?,第 3 个。什么实用程序?它甚至没有编译,我猜它缺少一些导入
    • @LuisValencia 你必须安装 Axios 才能运行上面的代码。我也添加了链接。您可以在表单数据中添加自定义对象。我已经添加了示例。
    • 正如我之前所说的,我需要使用 react adal。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2017-01-22
    • 2021-03-20
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多