【问题标题】:Asp.net WebAPI enable Cors to specific SSL/https originAsp.net WebAPI 启用 Cors 到特定的 SSL/https 来源
【发布时间】:2015-09-25 19:14:53
【问题描述】:

以下是我的 web api 项目的一部分。

public class TriviaController : ApiController
{        
    public HttpResponseMessage Get()
    {
        QuestionAnswer _QuestionAnswer = new QuestionAnswer();
        TriviaQuestion _TriviaQuestion = _QuestionAnswer.GetQuestion("test@yahoo.com");
        return Request.CreateResponse(HttpStatusCode.OK, _TriviaQuestion);
    }    
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        AddRoutes(config);
    }

    private static void AddRoutes(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*",
            headers: "*",
            methods: "*");
        config.EnableCors(cors);
    }
}

我的客户端应用程序接收到控制器返回的 json 数据。 在我修改为如下特定来源之前,一切正常。

var cors = new EnableCorsAttribute(
            origins: "https://jsfiddle.net/", //"https://localhost:44304/",
            headers: "*",
            methods: "*");

之后,我的客户端应用程序只收到空值和错误消息,显示状态代码为 0。
根据this reference link,我知道是因为CORS。

下面是我的客户端代码。就是这么简单。

alert("*");
$.getJSON("https://localhost:44300/api/trivia", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { 
alert('getJSON request failed! ' + textStatus + ' :: ' + jqXHR + ' :: ' + errorThrown); 

$.each(jqXHR, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

})
.always(function() { alert('getJSON request ended!'); });

要在 jsFiddle 上查看,请单击 here

所以我的问题是,
是否可以使用 SSL 设置允许来源?如果是这样,我做错了什么?

【问题讨论】:

  • 是的,绝对可以使用 SSL 允许来源。尝试从EnablesCorsAttribute origins 中删除最后一个正斜杠/
  • 谢谢@boosts,你是对的,我删除了/,然后我可以使用https://localhost:portno 调用。但我仍然不知道为什么像 jsfiddle 这样的外部 url 仍然不能。可能是我使用的是没有域且只有不受信任的 SSL 证书的 IIS express。请提供更多建议!

标签: c# asp.net-web-api cors


【解决方案1】:

尝试单独添加来源。在您的浏览器中使用开发者工具来确保来源与您想要的完全匹配。

var cors = new EnableCorsAttribute("https://localhost:portno", "*", "*"); // local
cors.Origins.Add("https://jsfiddle.net");  // jsfiddle

config.EnableCors(cors);

【讨论】:

  • 谢谢@boosts,+1 投票给你的好建议Use Developer Tools in your browser to make sure that the origins match exactly to what you intend them to be。实际上jsfiddle.net 使用https://fiddle.jshell.net。最后,我可以根据您的建议解决它。
  • var cors = new EnableCorsAttribute( origins: "https://fiddle.jshell.net,https://localhost:44303", headers: "*", methods: "*");
猜你喜欢
  • 2017-02-22
  • 2020-04-19
  • 2012-12-29
  • 2021-04-09
  • 2021-12-30
  • 2021-07-27
  • 2020-09-07
  • 1970-01-01
相关资源
最近更新 更多