c# - REST PUT 似乎无法连接到服务器

标签 c# javascript jquery asp.net rest

[已解决]

Subir Kumar Sao完全正确,这是一个 CORS 问题,而不是客户端问题,万一其他人通过托管用 C# 编码的服务器遇到同样的问题,这将是解决方案:

CORS support for ASP.NET Web API 获取程序集并将它们引用到您的服务器项目,然后在 HttpSelfHostConfiguration 下插入以下内容,最终如下所示:

var config = new HttpSelfHostConfiguration ("http://10.0.5.106:8000");

var enableCorsAttribute = new EnableCorsAttribute ("*", "*", "*")
{
    SupportsCredentials = true
};
config.EnableCors (enableCorsAttribute);
<小时/>

[问题]

我正在运行一个使用 C#VS2013 编写的服务器,用于使用 KineticJS 在 Canvas 中托管的 LED 灯控制应用程序。

我使用 ChromePostman 扩展对其进行了测试,它工作完美,我可以 GET,也可以 PUT。

因为这是我第一次使用 REST 进行编码,所以我决定使用 jQuery 中的 .ajax,它似乎有很好的文档记录。但由于某种奇怪的原因,它不起作用,我很茫然,因为也许我错过了一些东西,而且我也无法检查发生了什么,因为从“错误”返回的前值为空。

这是我在客户端使用的代码:

$.ajax({
    url: 'http://10.0.5.106:8000/api/LED/Save',
    type: 'PUT',
    data: { N: '1', Pos: '10' },
    success: function() { alert('PUT completed'); },
    error: function(req,status,ex){alert(ex);}
});

为了了解我的服务器的结构,这里还有它的代码:

private static void RestServer()
{
    var config = new HttpSelfHostConfiguration ("http://10.0.5.106:8000");

    config.MapHttpAttributeRoutes ();
    HttpSelfHostServer server = new HttpSelfHostServer (config);
    server.OpenAsync ().Wait ();
    while (true) {
    }
}

[RoutePrefix ("api/LED")]
public class LEDController : ApiController
{
    [Route ("Save")]
    public HttpResponseMessage PutSave(int N, int Pos)
    {
        return Request.CreateResponse (HttpStatusCode.NoContent);
    }

    [Route ("Load")]
    public HttpResponseMessage PutLoad(int N, int Pos)
    {
        return Request.CreateResponse (HttpStatusCode.NoContent);
    }
    [Route ("Intense")]
    public HttpResponseMessage PutInt(int N, int I)
    {
        return Request.CreateResponse (HttpStatusCode.NoContent);
    }
    [Route ("RGB")]
    public HttpResponseMessage PutRGB(int N, int R, int G, int B, int I)
    {
        return Request.CreateResponse (HttpStatusCode.NoContent);
    }
}

最佳答案

这似乎是 CORS 问题。

了解更多 here .

并阅读here关于如何启用 CORS。

关于c# - REST PUT 似乎无法连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23367877/

相关文章:

javascript - 防止用户在手机上横向浏览网站

javascript - 使用 Masonry 布置元素

javascript - jquery mobile History.back() 仅在第一次时有效

c# - 使用 FindControl 填充文本框

c# - 如何将 JSON.Net 中的 JObject 转换为 T

javascript - 使用 1 个脚本禁用多个 key

jquery - CSS/jQuery : How to prevent tooltip from disappearing behind border of main wrapper (working code)

c# - Xam.Plugin.Connectivity(作者 James Montemagno)无视提供的超时

c# - 互操作词动态表创建

jquery - 使用 jquery 替换通配 rune 本