本文介绍了如何使用FileUpload向Azure AD受保护的REST API进行REST API发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下.net WEB API

I have the following .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 App调用Put Tenand端点.

And I need to call the Put Tenand endpoint from a React App.

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

In my react app, I already tested a single GET endpoint, like this:

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

My 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中知道如何将表单放入inout元素,捕获值和最重要的元素,将文件发送到端点.

Now I need to know in React, how to put the form inout elements, capture the value and the most important one, send a file to the endpoint.

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>
    );
  }
}

推荐答案

adalFetch函数接受一个fetch对象,您可以选择使用任何npm包(例如fetch或Axios)并将其传递.请从react-adal存储库中引用此 issue .在这里,我正在编写一个小片段,以发送具有上传进度的文件.

The adalFetch function takes a fetch object, you can choose to use any npm package like fetch or Axios and pass it on. Refer the this issue from the react-adal repository. Here I'm writing a small snippet to send file with upload progress.

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在asp.net mvc中上传文件

For the ASP.net side please refer the following answer jQuery ajax upload file in asp.net mvc

这篇关于如何使用FileUpload向Azure AD受保护的REST API进行REST API发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:50