带有POST请求的415(不受支持的媒体类型)

时间:2018-08-08 20:20:05

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

我有一个react组件,当按下一个复选框时,它将调用rest api,使用单个参数发布请求。

我在webapi中放置了一个断点,但它从未命中,但在组件上我仍然得到415非支持的媒体类型

react js component (see onchange event)

import React, { Component } from 'react';
import {  Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';

class ListTenants extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }



    fetchData = () => {
        adalApiFetch(fetch, "/Tenant", {})
          .then(response => response.json())
          .then(responseJson => {
            if (!this.isCancelled) {
                const results= responseJson.map(row => ({
                    key: row.ClientId,
                    ClientId: row.ClientId,
                    ClientSecret: row.ClientSecret,
                    Id: row.Id,
                    SiteCollectionTestUrl: row.SiteCollectionTestUrl,
                    TenantDomainUrl: row.TenantDomainUrl
                  }))
              this.setState({ data: results });
            }
          })
          .catch(error => {
            console.error(error);
          });
      };


    componentDidMount(){
        this.fetchData();
    }

    render() {
        const columns = [
                {
                    title: 'Client Id',
                    dataIndex: 'ClientId',
                    key: 'ClientId'
                }, 
                {
                    title: 'Site Collection TestUrl',
                    dataIndex: 'SiteCollectionTestUrl',
                    key: 'SiteCollectionTestUrl',
                },
                {
                    title: 'Tenant DomainUrl',
                    dataIndex: 'TenantDomainUrl',
                    key: 'TenantDomainUrl',
                }
        ];

        // rowSelection object indicates the need for row selection
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                if(selectedRows[0].key != undefined){
                    console.log(selectedRows[0].key);


                    const options = { 
                        method: 'post', 
                        body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
                        config: {
                            headers: {
                              'Content-Type': 'application/json'
                            }
                          }
                    };

                    adalApiFetch(fetch, "/Tenant/SetTenantActive", options)
                        .then(response =>{
                        if(response.status === 200){
                            Notification(
                                'success',
                                'Tenant set to active',
                                ''
                                );
                        }else{
                            throw "error";
                        }
                        })
                        .catch(error => {
                        Notification(
                            'error',
                            'Tenant not activated',
                            error
                            );
                        console.error(error);
                    });
                }
            },
            getCheckboxProps: record => ({
                type: Radio
            }),
        };

        return (
            <Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} />
        );
    }
}

export default ListTenants;

和webapi方法

[HttpPost]
        [Route("api/Tenant/SetTenantActive")]
        public async Task<IHttpActionResult> SetTenantActive([FromBody]string clientid)
        {
            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            var allTenants = await tenantStore.Query().Where(x => x.TenantDomainUrl != null).ToListAsync();
            foreach(Tenant ten  in allTenants)
            {
                ten.Active = false;
                await tenantStore.UpdateAsync(ten);
            }

            var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.clientid == clientid);
            if (tenant == null)
            {
                return NotFound();
            }

            tenant.Active = true;
            var result = await tenantStore.UpdateAsync(tenant);

            return Ok(result);
        }

5 个答案:

答案 0 :(得分:3)

我注意到的事情。

  1. 您正在尝试使用JSON正文进行POST请求。在客户端上,您的请求看起来不错。

据我所知POST正文是

{ clientid: 'some-client-id' }
  1. 有趣的是,您在Web API中收到的邮件是

public async Task<IHttpActionResult> SetTenantActive([FromBody]string clientid)

这可能是罪魁祸首。您的API期望将字符串作为POST主体,其中是json对象。您是否尝试过将类型更改为dynamicJObject

因此,基本上,

public async Task<IHttpActionResult> SetTenantActive([FromBody]dynamic clientRequest)

OR

public async Task<IHttpActionResult> SetTenantActive([FromBody]JObject clientRequest)

或者,

如果您想按原样继续使用API​​,则可以将客户端发出的请求更改为’some-client-id’,而不是{ clientid: 'some-client-id' }

答案 1 :(得分:1)

更改

const options = { 
    method: 'post', 
    body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
    config: {
        headers: {
            'Content-Type': 'application/json'
        }
    }
};

const options = { 
    method: 'post', 
    body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
};

答案 2 :(得分:1)

检查服务器设置。默认情况下,它应支持$this->db->select('express_interests.*, cl_to.User_Name AS ToClient, cl_from.User_Name AS FromClient, cl_from.Member_Id AS FromMid, cl_to.Member_Id AS ToMid '); ,但最好对其进行验证。另外,请尝试清除api代码中的json标头,并将其设置为Accept,这意味着所有类型。

此外,检查*方法。它发送什么头? adalApiFetch的格式是否正确使用和设置?

答案 3 :(得分:1)

对于像这样的简单RESTFul调用,您可以遵循建议命名约定以及HTTP动词,以更好地阐明意图并简化调用本身。如此简单的调用无需过度复杂化API模型。

类似

[HttpPut] // Or HttpPost. PUT is usually used to update the resourcce
[Route("api/Tenant/{clientid}/Active")]
public async Task<IHttpActionResult> SetTenantActive(string clientid) {
    var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
    var allTenants = await tenantStore.Query().Where(x => x.TenantDomainUrl != null).ToListAsync();
    var updates = new List<Task>();
    foreach(Tenant ten  in allTenants) {
        ten.Active = false;
        updates.Add(tenantStore.UpdateAsync(ten));
    }

    await Task.WhenAll(updates);

    var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.clientid == clientid);
    if (tenant == null)
    {
        return NotFound();
    }

    tenant.Active = true;
    var result = await tenantStore.UpdateAsync(tenant);

    return Ok(result);
}

在客户端上

const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
        if(selectedRows[0].key != undefined){
            var clientid = selectedRows[0].key;
            console.log(clientid);

            var url = "/Tenant/" + clientid + "/Active"

            const options = { 
                method: 'put'
            };

            adalApiFetch(fetch, url, options)
                .then(response => {
                if(response.status === 200){
                    Notification(
                        'success',
                        'Tenant set to active',
                        ''
                        );
                }else{
                    throw "error";
                }
                })
                .catch(error => {
                Notification(
                    'error',
                    'Tenant not activated',
                    error
                    );
                console.error(error);
            });
        }
    },
    getCheckboxProps: record => ({
        type: Radio
    }),
};

答案 4 :(得分:0)

您为什么要使用post?从“ REST” y的角度来看,它用于创建实体(在您的情况下为租户)。

可以通过GET并将clientid作为路由的一部分来解决预期的简单请求:

[HttpGet]
[Route("api/Tenant/SetTenantActive/{clientid}")]
public async Task<IHttpActionResult> SetTenantActive(string clientid)
{
   // ...
}