在Windows窗体中配置webapi以接受CROS
本文关键字:CROS webapi 配置 Windows 窗体 | 更新日期: 2023-09-27 18:18:04
我正在为大学做一个项目,其中一个网站向Windows窗体应用程序发送命令。该应用程序负责访问串行端口并发送和接收命令。
网站与Windows窗体应用程序之间的通信,我使用了Web Api。我需要设置webapi实现CORS,但我所看到的所有例子都是为MVC,我需要Windows窗体。我下了订单,我从客户端调用和如何webapi在我的Windows窗体配置。
还有,把Chrome返回给我的错误。
类WebApi与Windows窗体
public class GPSController : ApiController
{
[HttpGet]
public Coordenada Posicao()
{
return TCCWindows.FormPrincipal.PegarCoordenadas();
}
}
Configuration WebApi Windows Forms
private void button2_Click_2(object sender, EventArgs e)
{
if (button2.Text == "Iniciar serviço")
{
var config = new HttpSelfHostConfiguration(textBox1.Text);
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
server = new HttpSelfHostServer(config);
server.OpenAsync();
MessageBox.Show("Serviço inicializado!");
button2.Text = "Parar serviço";
}
else
{
server.CloseAsync();
button2.Text = "Iniciar serviço";
}
}
Get WebApi Jquery my MVC Site
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost:8089/api/gps/",
success: function(callback){
alert(callback);
},
error: function(err){
alert("You have a error"+err);
}
});
}
Get cmdLocal, with Chrome
XMLHttpRequest cannot load http://localhost:8089/api/gps/. Origin http://localhost:36452 is not allowed by Access-Control-Allow-Origin.
如何在Windows窗体应用程序中实现CORS ?
谢谢
如果CORS支持是作为DelegatingHandler实现的,那么它与Web Host和self Host之间的使用方式应该没有区别。唯一的问题是,如果CORS实现依赖于HttpContext
。
你想使用什么CORS实现?
顺便说一句,你的windows窗体应用程序将需要运行作为管理员的什么你试图做的工作