405(不允许方法)在reactjs组件上

时间:2018-09-16 11:42:17

标签: javascript .net reactjs asp.net-web-api asp.net-web-api2

我正在尝试使用post方法调用终结点。

代码是:

import React, { Component } from 'react';
import { Input} from 'antd';
import Form from '../../components/uielements/form';
import Button from '../../components/uielements/button';
import Notification from '../../components/notification';
import { adalApiFetch } from '../../adalConfig';


const FormItem = Form.Item;

class CreateSiteCollectionForm extends Component {
    constructor(props) {
        super(props);
        this.state = {Alias:'',DisplayName:'', Description:''};
        this.handleChangeAlias = this.handleChangeAlias.bind(this);
        this.handleChangeDisplayName = this.handleChangeDisplayName.bind(this);
        this.handleChangeDescription = this.handleChangeDescription.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    };

    handleChangeAlias(event){
        this.setState({Alias: event.target.value});
    }

    handleChangeDisplayName(event){
        this.setState({DisplayName: event.target.value});
    }

    handleChangeDescription(event){
        this.setState({Description: event.target.value});
    }

    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let data = new FormData();
                //Append files to form data
                //data.append(

                const options = {
                  method: 'post',
                  body: JSON.stringify(
                    {
                        "Alias": this.state.Alias,
                        "DisplayName": this.state.DisplayName, 
                        "Description": this.state.Description
                    }),
                  config: {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                };

                adalApiFetch(fetch, "/SiteCollections/CreateModernSite", options)
                  .then(response =>{
                    if(response.status === 204){
                        Notification(
                            'success',
                            'Site collection created',
                            ''
                            );
                     }else{
                        throw "error";
                     }
                  })
                  .catch(error => {
                    Notification(
                        'error',
                        'Site collection not created',
                        error
                        );
                    console.error(error);
                });
            }
        });      
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
        };
        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 14,
            offset: 6,
            },
        },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="Alias" hasFeedback>
                {getFieldDecorator('Alias', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your alias',
                        }
                    ]
                })(<Input name="alias" id="alias" onChange={this.handleChangeAlias} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Display Name" hasFeedback>
                {getFieldDecorator('displayname', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your display name',
                        }
                    ]
                })(<Input name="displayname" id="displayname" onChange={this.handleChangedisplayname} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Description" hasFeedback>
                {getFieldDecorator('description', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your description',
                        }
                    ],
                })(<Input name="description" id="description"  onChange={this.handleChangeDescription} />)}
                </FormItem>

                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">
                        Create modern site
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedCreateSiteCollectionForm = Form.create()(CreateSiteCollectionForm);
export default WrappedCreateSiteCollectionForm;

和webapi是这样的:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using TenantManagementWebApi.Entities;
using TenantManagementWebApi.Factories;
using Cosmonaut.Extensions;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Sites;
using TenantManagementWebApi.Components;

namespace TenantManagementWebApi.Controllers
{
    [Authorize]
    public class SiteCollectionsController : ApiController
    {
        // GET: ModernTeamSite
        public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
        {
            var tenant = await TenantHelper.GetTenantAsync();

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret))
            {
                Tenant tenantOnline = new Tenant(cc);
                SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
                cc.Load(siteProps);
                cc.ExecuteQuery();
                List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
                foreach (var site in siteProps)
                {

                    sites.Add(new TenantManagementWebApi.Entities.SiteCollection()
                    {
                        Url = site.Url,
                        Owner = site.Owner,
                        Template = site.Template,
                        Title = site.Title
                    });
                }

                return sites;
            };
        }

        [HttpPost]
        //[Route("api/SiteCollections/CreateModernSite")]
        public async Task<string>  CreateModernSite(string Alias, string DisplayName, string Description)
        {
            var tenant = await TenantHelper.GetTenantAsync();
            using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret))
            {
                 var teamContext = await context.CreateSiteAsync(
                    new TeamSiteCollectionCreationInformation
                    {
                        Alias = Alias, // Mandatory
                        DisplayName = DisplayName, // Mandatory
                        Description = Description, // Optional
                        //Classification = Classification, // Optional
                        //IsPublic = IsPublic, // Optional, default true
                    }
                );
                teamContext.Load(teamContext.Web, w => w.Url);
                teamContext.ExecuteQueryRetry();
                return teamContext.Web.Url;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

尝试将您的Post请求参数移到这样的类中

public class TeamSiteInformation
{
    public string Alias { get; set; }
    public string DisplayName  { get; set; }
    public string Description   { get; set; }
}

并将您的方法CreateModernSite签名修改为

[HttpPost]
public void CreateModernSite([FromBody]TeamSiteInformation site_info)
{

,然后在reactjs应用中将“ Content-Type”:“ multipart / form-data”更改为“ application / json”

答案 1 :(得分:1)

根据评论中张贴的屏幕快照,启用了属性路由,因为WebApiConfig具有默认配置

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

请注意基于约定的路由上的api前缀。

正在向/SiteCollections/CreateModernSite发送来自客户端的请求,该请求与Web API不匹配,因为API控制器似乎未使用属性路由,并且所请求的URL与基于Web API约定的路由不匹配。

还在客户端,当内容类型设置为'multipart/form-data'时,在选项中构造了JSON正文

如果打算在正文中发布内容,那么在服务器端,您需要进行一些更改以使API可以访问。

[Authorize]
[RoutePrefix("api/SiteCollections")]
public class SiteCollectionsController : ApiController {
    // GET api/SiteCollections
    [HttpGet]
    [Route("")]
    public async Task<IHttpActionResult> Get() {
        var tenant = await TenantHelper.GetTenantAsync();
        using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret)) {
            var tenantOnline = new Tenant(cc);
            SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
            cc.Load(siteProps);
            cc.ExecuteQuery();
            var sites = siteProps.Select(site => 
                new TenantManagementWebApi.Entities.SiteCollection() {
                    Url = site.Url,
                    Owner = site.Owner,
                    Template = site.Template,
                    Title = site.Title
                })
                .ToList();
            return Ok(sites);
        }
    }

    // POST api/SiteCollections
    [HttpPost]
    [Route("")]
    public async Task<IHttpActionResult>  CreateModernSite([FromBody]NewSiteInformation model) {
        if(ModelState.IsValid) {
            var tenant = await TenantHelper.GetTenantAsync();
            using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret)) {
                 var teamContext = await context.CreateSiteAsync(
                    new TeamSiteCollectionCreationInformation {
                        Alias = model.Alias, // Mandatory
                        DisplayName = model.DisplayName, // Mandatory
                        Description = model.Description, // Optional
                        //Classification = Classification, // Optional
                        //IsPublic = IsPublic, // Optional, default true
                    }
                );
                teamContext.Load(teamContext.Web, _ => _.Url);
                teamContext.ExecuteQueryRetry();
                //204 with location and content set to created URL
                return Created(teamContext.Web.Url, teamContext.Web.Url);
            }
        }
        return BadRequest(ModelState);
    }

    public class NewSiteInformation {
        [Required]
        public string Alias { get; set; }
        [Required]
        public string DisplayName { get; set; }
        public string Description { get; set; }
        //...
    }
}

请注意为POST操作包括适当的强类型对象模型,模型验证以及如客户端期望的那样返回适当的HTTP状态代码。 (204)

在客户端,更新被调用的URL以匹配API控制器的路由,并更新选项以发送正确的内容类型。

//...

const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(
    {
        Alias: this.state.Alias,
        DisplayName: this.state.DisplayName, 
        Description: this.state.Description
    })      
};

adalApiFetch(fetch, "api/SiteCollections", options)
  .then(response =>{
    if(response.status === 204){
        Notification(
            'success',
            'Site collection created',
            ''
            );
     }else{
        throw "error";
     }
  })
  .catch(error => {
    Notification(
        'error',
        'Site collection not created',
        error
        );
    console.error(error);
});

//...

请注意,如何将headers直接置于原始代码中与config.headers相对的获取选项中。