【问题标题】:415 Media not supported, calling post REST endpoint415 不支持媒体,正在调用 post REST 端点
【发布时间】:2019-04-01 02:19:36
【问题描述】:

我正在尝试从 reactjs 调用 webapi,但出现此错误:

415 不支持媒体,正在调用 post REST 端点

   [HttpPost]
            [Route("")]
            //[Route("api/SiteCollections/CreateModernSite")]
            public async Task<IHttpActionResult> CreateModernSite([FromBody]NewSiteInformation model)
            {

                if (ModelState.IsValid)

                {
                    AuthenticationManager auth = new AuthenticationManager();
                    auth.GetSharePointOnlineAuthenticatedContextTenant("url", "user", "password");


                    var tenant = await TenantHelper.GetTenantAsync();
                    using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://luisevalencia38.sharepoint.com/teamsite1/SitePages/Home.aspx", "luisevalencia38@luisevalencia38.onmicrosoft.com", "Vaz.717."))
                    {
                        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);
            }

我的反应代码是这样的:

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': 'application/json; charset=utf-8'
                    }
                  }
                };

                adalApiFetch(fetch, "/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);
                });
            }
        });      
    }

    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;

如何避免:调用端点时出现 415 媒体不支持?我的错误是在客户端代码上还是在 webapi 上?

【问题讨论】:

  • 已更新,以防万一不清楚
  • 标签中有核心 web api,但所有代码看起来都像 web api2。这是一个错误吗?
  • 在配置 Web Api Formatter 时检查是否对其进行了任何更改。 (WebApiConfig)
  • 不,该文件是默认文件,我假设 .net api 核心几乎相同,所以我标记了它
  • 由于某种原因内容类型变为:text/plain;charset=UTF-8

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


【解决方案1】:

尝试使用这个

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

另见question,似乎no-cors 请求不允许覆盖Content-Type 请求标头。

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2021-04-18
    • 1970-01-01
    • 2018-06-11
    • 2019-01-16
    • 2019-04-18
    • 2020-09-03
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多