Javascript reactjs组件上的405(不允许使用方法)
我正在尝试使用post方法调用端点 代码是:Javascript reactjs组件上的405(不允许使用方法),javascript,.net,reactjs,asp.net-web-api,asp.net-web-api2,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/not
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;
import React,{Component}来自'React';
从“antd”导入{Input};
从“../../components/uielements/Form”导入表单;
从“../../components/uielements/Button”导入按钮;
从“../../components/Notification”导入通知;
从“../../adalConfig”导入{adalApiFetch};
const FormItem=表单项;
类CreateSiteCollectionForm扩展组件{
建造师(道具){
超级(道具);
this.state={Alias:'',DisplayName:'',Description:''};
this.handleChangeAlias=this.handleChangeAlias.bind(this);
this.handleChangeDisplayName=this.handleChangeDisplayName.bind(this);
this.handlechangescription=this.handlechangescription.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
};
handleChangeAlias(事件){
this.setState({Alias:event.target.value});
}
handleChangeDisplayName(事件){
this.setState({DisplayName:event.target.value});
}
handleChangeDescription(事件){
this.setState({Description:event.target.value});
}
handleSubmit(e){
e、 预防默认值();
this.props.form.validateFieldsAndScroll((错误,值)=>{
如果(!err){
let data=new FormData();
//将文件附加到表单数据
//data.append(
常量选项={
方法:“post”,
正文:JSON.stringify(
{
“别名”:this.state.Alias,
“DisplayName”:this.state.DisplayName,
“描述”:this.state.Description
}),
配置:{
标题:{
“内容类型”:“多部分/表单数据”
}
}
};
adalApiFetch(获取“/sitecolections/CreateModernSite”,选项)
。然后(响应=>{
如果(response.status==204){
通知(
“成功”,
“已创建网站集”,
''
);
}否则{
抛出“错误”;
}
})
.catch(错误=>{
通知(
“错误”,
“未创建网站集”,
错误
);
控制台错误(error);
});
}
});
}
render(){
const{getFieldDecorator}=this.props.form;
常量formItemLayout={
labelCol:{
xs:{span:24},
sm:{span:6},
},
包装纸:{
xs:{span:24},
sm:{span:14},
},
};
常量tailFormItemLayout={
包装纸:{
xs:{
跨度:24,
偏移量:0,
},
sm:{
跨度:14,
抵销:6,
},
},
};
返回(
{getFieldDecorator('别名'{
规则:[
{
要求:正确,
消息:“请输入您的别名”,
}
]
})()}
{getFieldDecorator('displayname'{
规则:[
{
要求:正确,
消息:“请输入您的显示名称”,
}
]
})()}
{getFieldDecorator('description'{
规则:[
{
要求:正确,
消息:“请输入您的描述”,
}
],
})()}
创建现代网站
);
}
}
const WrappedCreateSiteCollectionForm=Form.create()(CreateSiteCollectionForm);
导出默认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;
}
}
}
}
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用System.Web.Http;
使用TenantManagementWebApi.Entities;
使用租户管理webapi.Factories;
使用宇航员扩展;
使用Microsoft.Online.SharePoint.TenantaAdministration;
使用Microsoft.SharePoint.Client;
使用OfficeDevPnP.Core.Sites;
使用TenantManagementWebApi.Components;
命名空间租户管理WebAPI.Controllers
{
[授权]
公共类SiteCollectionsController:ApiController
{
//获取:ModernTeamSite
公共异步任务Get()
{
var tenant=await TenantHelper.GetTenantAsync();
使用(var cc=new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.tenantAdministral、tenant.ClientId、tenant.ClientSecret))
{
租户在线=新租户(cc);
SPOSitePropertiesEnumerable siteProps=tenantOnline.GetSitePropertiesFromSharePoint(“0”,true);
cc.荷载(现场支柱);
cc.ExecuteQuery();
列表站点=新列表();
foreach(siteProps中的var站点)
{
添加(新租户管理WebAPI.Entities.SiteCollection()
{
Url=site.Url,
所有者=站点。所有者,
Template=site.Tem
public class TeamSiteInformation
{
public string Alias { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
}
[HttpPost]
public void CreateModernSite([FromBody]TeamSiteInformation site_info)
{
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 }
);
}
}
[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; }
//...
}
}
//...
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);
});
//...