使用HTTP Post (RESTful API)从React.JS前端传递请求到c#后端(ASP.NET)



很抱歉,这个标题很乱-我是web开发的新手,不确定如何最好地表达这个。

<标题>我的目标
  • 我想点击一个按钮在我的React.js前端,并有c#后端激活GPIO响应。
  • 经过研究,我想使用HTTP Post功能,但我不确定从哪里开始。
  • 简而言之:我想从我的React.js前端调用一个c#函数

What I Have so far:

  • React.JS文件:RoomComponent.js
import React, { Component } from 'react';
export class RoomComponent extends Component {
static displayName = RoomComponent.name;
constructor(props) {
super(props);
this.state = { lightOn: true };
this.turnOnLight = this.turnOnLight.bind(this);
}
componentDidMount() {
// call turn on light function, where HTTP post is used to send on signal to back-end
}
render() {
return (
<div>
<button className="btn btn-primary" onClick={this.turnOnLight}>Toggle LED</button>
</div>
);
}
async turnOnLight() {
// here i would use HTTP post with a "fetch" function? How do I send data here?
alert("LED toggled");
}
}
  • c# file:Lighting.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Device.Gpio;
using System.Net.Http;

namespace control.Controllers
{
[ApiController]
[Route("[controller]")]
public class LightingController : ControllerBase
{
private readonly int ledPin = 11;
private GpioController controller = new GpioController();
private static readonly HttpClient client = new HttpClient();

[HttpPost]
public void turnOnLed()
{
// somehow recieve JSON with data telling the GPIO to turn on, and activate it accordingly
controller.Write(ledPin, PinValue.High);
}
public LightingController()
{
controller.OpenPin(ledPin, PinMode.Output);
}
}
}

Where I'm struggle

我很难理解我将如何制定HTTP Post与我想要激活GPIO的后端通信。在线的例子总是HTTP发布/从远程url获取信息,但对我来说,它都包含在同一个应用程序中。我会非常感激任何建议或指导与此,甚至其他资源,以帮助我更好地了解如何去做这个。

谢谢!

如果我没弄错的话,你正在使用。net core。

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Device.Gpio;
using System.Net.Http;
namespace control.Controllers
{
[ApiController]
//[Route("[controller]")] Remove this
public class LightingController : ControllerBase
{
private readonly int ledPin = 11;
private GpioController controller = new GpioController();
private static readonly HttpClient client = new HttpClient();

//And add the route attribute to your endpoint
[Route("api/turnOnLed")]
[HttpPost]
public void turnOnLed()
{
// somehow recieve JSON with data telling the GPIO to turn on, and activate it accordingly
controller.Write(ledPin, PinValue.High);
}
public LightingController()
{
controller.OpenPin(ledPin, PinMode.Output);
}
}

基本上就是删除Route("Controller")属性,然后将其添加到端点,但要使用"api/[端点名称]"也就是turnOnLed。应该可以。

最新更新