【问题标题】:React axios post request to wcf web service将 axios 发布请求反应到 wcf Web 服务
【发布时间】:2020-09-07 06:11:23
【问题描述】:

我正在尝试将数据从反应应用程序发布到 wcf 服务类。它是一个简单的对象,只有名称年龄和性别。正在从反应应用程序调用该服务,但没有数据。如果我使用获取请求和参数传递数据正在传递给服务,但我想使用发布请求。是否需要像 wcf 服务类一样匹配字段名。

为了在反应组件中进行测试,我正在使用此代码

const headers = {
            'content-type': 'application/json'
          }

    const puser = {
      Name:'Test',
      Age:'23',
      Gender:'F',
    }
    axios.post('http://localhost:3292/myService.svc/adduser',{headers:headers}, puser)
    .then(res=> {
      console.log(res.data)
    })

在 wcf 服务中,类代码是

public class UserClass
    {

        string name;
        int age;
        string gender;

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
            }
        }

        public int Age
        {
            get
            {
                return age;
            }

            set
            {
                age = value;
            }
        }

        public string Gender
        {
            get
            {
                return gender;
            }

            set
            {
                gender = value;
            }
        }
}

正在服务中

public string AddUser(List<User> U)
        {
            UserClass usr = new UserClass();
        return "success";
    }

【问题讨论】:

  • 您使用了错误的参数位置。 body data 应该是第二个参数,config 应该是第三个参数。这是 axios.post 签名axios.post(url[, data[, config]])
  • 您的服务需要一个用户数组,但您发送了一个用户对象。
  • 尝试用数据切换标题并尝试制作对象数组并传输它,但后端服务仍然没有收到数据。
  • 您好,问题解决了吗?如果您认为我的回复对您有帮助,您可以将其标记为答案。

标签: reactjs api class object wcf


【解决方案1】:

Axios post 方法需要 data 作为第二个参数。尝试将puser{headers} 交换。 https://github.com/axios/axios#axiosposturl-data-config

【讨论】:

  • 试过了,还是服务没有收到数据
【解决方案2】:

不要在 axios.post 中添加 header,代码应该是这样的:

    const puser = {
      Name:'Test',
      Age:'23',
      Gender:'F',
    }
    axios.post('http://localhost:8000/AddUser', puser)
    .then(res=> {
      console.log(res.data)
    })

如果问题仍然存在,请随时告诉我。

更新:

在 Postman 中设置标题:

axios.post 也可以像下面这样设置header:

axios.post('http://localhost:8000/AddUser',{ Name:'Test',
  Age:'2311',
  Gender:'FF'}, {headers: {
       'content-type': 'application/json'
    }})
.then(res=> {
  console.log(res.data)
})

这是我的项目:

程序.cs:

using Demo_rest_ConsoleApp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp71
{
    public class User
    {

        string name;
        int age;
        string gender;

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
            }
        }

        public int Age
        {
            get
            {
                return age;
            }

            set
            {
                age = value;
            }
        }

        public string Gender
        {
            get
            {
                return gender;
            }

            set
            {
                gender = value;
            }
        }
    }
    [ServiceContract]
    [CustContractBehavior]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
        [OperationContract]
        [WebInvoke(ResponseFormat =WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json)]
        string AddUser(User U);
       
    }
    public class Service : IService
    {
        public string AddUser(User U)
        {

            Console.WriteLine(U.Age);
            Console.WriteLine(U.Gender);
            Console.WriteLine(U.Name);
            return "success";
        }

        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
            ep.EndpointBehaviors.Add(new WebHttpBehavior() { HelpEnabled=true});
            host.Open();
            Console.WriteLine("Open");
            Console.ReadLine();
        }
    }
}

Soap.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;

namespace Demo_rest_ConsoleApp
{
    public class ServerMessageLogger : IDispatchMessageInspector
    {
       
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            Console.WriteLine(request);
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {

            WebOperationContext ctx = WebOperationContext.Current;
            ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
            if (ctx.IncomingRequest.Method == "OPTIONS")
            {
               ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,POST,DELETE,OPTIONS");
                ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");

            }


        }
    }
    public class ClientMessageLogger : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {

        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {

            return null;
        }
    }
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false)]
    public class CustContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
    {
        public Type TargetContract => throw new NotImplementedException();

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            return;
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.MessageInspectors.Add(new ServerMessageLogger());
        }

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
            return;
        }
    }


}

【讨论】:

  • 邮递员显示此错误。异常消息是“传入消息具有意外的消息格式“原始”。该操作的预期消息格式为“Xml”、“Json”。我试过 JSON.stringify 但它不起作用。
  • 不,它不工作。我希望 wcf 没有变化,因为相同的服务正在使用 Angular 应用程序。从 react 应用发送数据一定有问题。
  • 我发了我的项目,你可以参考一下,可以正常访问了。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 2021-03-09
相关资源
最近更新 更多