简体   繁体   English

Asp.net WebAPI启用Cors到特定的SSL / https来源

[英]Asp.net WebAPI enable Cors to specific SSL/https origin

Below is part of my web api project. 以下是我的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);
    }
}

My client application receive json data which returned by contoller. 我的客户端应用程序接收由contoller返回的json数据。 Everything working correct until I modify to specific origins like below. 一切正常,直到我修改为如下所示的特定来源。

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

After that, my client application receive only null value and error message saying Status Code 0. 之后,我的客户端应用程序仅收到空值和错误消息,指出状态码0。
According to this reference link , I know that it is because of CORS. 根据此参考链接 ,我知道这是因为CORS。

Below is my client code. 以下是我的客户代码。 It is so simple. 很简单。

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!'); });

To see on jsFiddle, click here . 要在jsFiddle上查看,请单击此处

So my question is, 所以我的问题是
Is it possible to set allow origin using SSL? 是否可以使用SSL设置允许来源? If so what am I doning wrong? 如果是这样,我在做什么错?

Try adding the origins separately. 尝试分别添加原点。 Use Developer Tools in your browser to make sure that the origins match exactly to what you intend them to be. 在浏览器中使用开发人员工具,以确保原点与您希望的原点完全匹配。

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

config.EnableCors(cors);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM