自定义Web API上的POST 405(不允许使用方法)

时间:2019-02-10 12:29:41

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

我有以下反应代码来调用发布端点,webapi确实有发布,但我仍然不知道为什么会收到此错误

matches: 8
num1: 29
num2: 0
num3: 8
num4: 4
s1: /
s2: /
s3: rw,relatime shared:1
s4: ext4 /dev/sda4 rw,errors=remount-ro

和我的webapi代码

import React, { Component } from 'react';
import { Row, Col, Tabs, Menu, Dropdown, Button, Icon, message, Input } from 'antd';

import Form from '../../components/uielements/form';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { Cascader } from 'antd';
import { adalApiFetch } from '../../adalConfig';

import Notification from '../../components/notification';

const FormItem = Form.Item;
 class ExtractPageTemplate extends Component {
    constructor(props) {
        super(props);
        this.state = {options:[], loading:false, selectedOptions:[], description:''};
        this.loadData = this.loadData.bind(this);
        this.enterLoading = this.enterLoading.bind(this);
        this.onChange = this.onChange.bind(this);
        this.handleChangeDescription= this.handleChangeDescription.bind(this);

    }

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

    enterLoading (){
        this.setState({ loading: true });

        const options = {
            method: 'post',
            body: JSON.stringify(
              {
                  "SiteCollectionUrl": this.state.selectedOptions[0].value,
                  "PageName": this.state.selectedOptions[1].label, 
                  "Description": this.state.Description
              }),
              headers: {
                  'Content-Type': 'application/json; charset=utf-8'
              } 
          };

          adalApiFetch(fetch, "/Page/CreatePageTemplate", options)
            .then(response =>{
              if(response.status === 204){
                  Notification(
                      'success',
                      'Page tempate created',
                      ''
                      );
               }else{
                  throw "error";
               }
            })
            .catch(error => {
              Notification(
                  'error',
                  'Page template not created',
                  error
                  );
              console.error(error);
          });

    }

    componentDidMount() {
        adalApiFetch(fetch, "/SiteCollection", {})
          .then(response => response.json())
          .then(json => {
            console.log(json);
            const firstLevelOptions = json.map(post => ({
                value: post.Url,
                label: post.Title,
                isLeaf: false    
            }));

            this.setState({
                options: firstLevelOptions
            });
          });
    }

    onChange(value, selectedOptions) {
        console.log("value:", value, "selectedOptions", selectedOptions);
        this.setState({
            selectedOptions: selectedOptions
        });
    }

    loadData(selectedOptions){
        console.log("loaddata", selectedOptions);

        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;

        const options = {
            method: 'get',
              headers: {
                      'Content-Type': 'application/json; charset=utf-8'
              }                    
          };

        adalApiFetch(fetch, "/Page/"+encodeURIComponent(targetOption.value.replace("https://","")), options)
          .then(response => response.json())
          .then(json => {
            targetOption.loading = false;
            console.log(json);
            const secondLevelOptions = json.map(page => ({
                value: page.Id,
                label: page.Name,
                isLeaf: true    
            }));
            targetOption.children = secondLevelOptions;
            this.setState({
                options: [...this.state.options],
            });
            }
        );

    }

    render(){

        console.log("uepa" , this.props);
        const { rowStyle, colStyle, gutter } = basicStyle;
        const TabPane = Tabs.TabPane;
        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 (
        <div>
            <LayoutWrapper>
            <PageHeader>{<IntlMessages id="pageTitles.PageAdministration" />}</PageHeader>
            <Row style={rowStyle} gutter={gutter} justify="start">
            <Col md={12} sm={12} xs={24} style={colStyle}>
                <Box
                title={<IntlMessages id="pageTitles.siteCollectionsTitle" />}
                subtitle={<IntlMessages id="pageTitles.siteCollectionsTitle" />}
                >
                <ContentHolder>
                    <Cascader
                                options={this.state.options}
                                loadData={this.loadData}
                                onChange={this.onChange}
                                changeOnSelect
                    />

                <FormItem {...formItemLayout} label="Description " hasFeedback>
                {getFieldDecorator('Description', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input the page template description',
                        }
                    ]
                })(<Input name="Description" id="Description" onChange={this.handleChangeDescription} />)}
                </FormItem>


                    <Button type="primary" loading={this.state.loading} onClick={this.enterLoading}>
                            Click me!
                            </Button>


                </ContentHolder>
                </Box>
            </Col>
            </Row>
        </LayoutWrapper>
        </div>
        );
  }
}

const WrappedExtractPageTemplate = Form.create()(ExtractPageTemplate );
export default WrappedExtractPageTemplate;

get端点工作正常

1 个答案:

答案 0 :(得分:1)

如果要访问CreatePageTemplate操作,则必须请求以下格式的url:RoutePrefix + Route。对于您来说,结果网址应为api/Page + api/Page/CreatePageTemplate = api/Page/api/Page/CreatePageTemplate。但是显然,这段代码

adalApiFetch(fetch, "/Page/CreatePageTemplate", options)

请求api/Page/CreatePageTemplate。因此,只需将其更新为以下内容

adalApiFetch(fetch, "/Page/api/Page/CreatePageTemplate", options)

但是,如果您打算使用原始网址,则只能更新操作

[HttpPost]
[Route("CreatePageTemplate")] //remove api/Page as it is already in RoutePrefix
public async Task<IHttpActionResult> CreatePageTemplate([FromBody]PageTemplateCreationModel model)