简体   繁体   English

MVC Azure + AjaxCall + microsofttranslator +对预检请求的响应未通过访问控制检查:它没有HTTP ok状态

[英]MVC Azure + AjaxCall + microsofttranslator + Response to preflight request doesn't pass access control check: It does not have HTTP ok status

    public async Task<string> accountLockUnlock(string wordtobeConverted)
    {
        try
        {
            var translatedText = "";
            while (true)
            {
                translatedText = await Translate(wordtobeConverted, "en");
                return translatedText;
            }
        }
        catch (Exception ex)
        {
            //CreateConsentsResponse consents = new CreateConsentsResponse();
            //consents.id = ex.Message.ToString();
            //return consents;
            throw new Exception(ex.Message.ToString());
        }
    }

    public static async Task<string> Translate(string text, string language)
    {
        var encodedText = WebUtility.UrlEncode(text);
        var uri = "https://api.microsofttranslator.com/V2/Http.svc/Translate?" +
            $"to={language}&text={encodedText}";
        var result = await client.GetStringAsync(uri);
        return XElement.Parse(result).Value;
    }
    private const string key = "Key";
    private static readonly HttpClient client = new HttpClient
    {
        DefaultRequestHeaders = { { "Ocp-Apim-Subscription-Key", key } }
    };

After Hosting if try to call from PostMan, am getting Proper Result Sample Calling : azurewebsites.net/.../Ciao Result we are getting as "HELLO", So no issue till here 在主持之后,如果尝试从PostMan打电话,我得到正确的结果样本呼叫:azurewebsites.net /.../Ciao结果我们得到“HELLO”,所以没有问题,直到这里

If i try calling the same URL azurewebsites.net/.../Ciao from Ajax call am getting " Response to preflight request doesn't pass access control check: It does not have HTTP ok status" 如果我尝试从Ajax调用相同的URL调用azurewebsites.net /.../Ciao,我将收到“对预检请求的响应未通过访问控制检查:它没有HTTP ok状态”

My Ajax Call: 我的Ajax电话:

var settings = { "async": true, "crossDomain": true, "url": "azurewebsites.net/.../Ciao", "method": "GET", "headers": { "cache-control": "no-cache", "Access-Control-Allow-Headers": "*" }}$.ajax(settings).done(function (response){console.log(response); }); var settings = {“async”:true,“crossDomain”:true,“url”:“azurewebsites.net /.../Ciao”​​,“method”:“GET”,“headers”:{“cache-control” :“no-cache”,“Access-Control-Allow-Headers”:“*”}} $。ajax(settings).done(function(response){console.log(response);});

Could any one help me here? 有人可以帮我吗?

The reason for the above is referred to CORS (Cross Origin Resource Sharing) 上述原因参考CORS(跨源资源共享)

there are several tips and tricks available in plural sites for CORS. CORS的多个站点提供了一些提示和技巧。 Check those out here 检查一下这里

There are several ways to address the issue, let's walk through step by step. 有几种方法可以解决这个问题,让我们一步一步地解决。

1: Adding the following customHeaders to the web.config of the Web API server. 1:将以下customHeaders添加到Web API服务器的web.config中。

<httpprotocol>
    <customheaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
    </customheaders>
</httpprotocol>

After adding the above keys, try running the client application the issue won't be resolved. 添加上述密钥后,尝试运行客户端应用程序,问题将无法解决。 The error can be seen in Developer Tool > Console Tab of Chrome. 可以在Chrome的“开发者工具”>“控制台”标签中看到该错误。

If Internet Explorer 10 or 11 is used, then in Console Tab, the following error can be seen. 如果使用Internet Explorer 10或11,则在“控制台”选项卡中,可以看到以下错误。

XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.

2: Remove the headers from the web.config mentioned above. 2:从上面提到的web.config中删除标题。

3: Search for CORS in Manage Nuget Packages in Visual Studio, I am using VS 2013. Make sure the Online at the left pane is selected and one can see Microsoft ASP.NET Web API 2.2 Cross-Origin Support and install that if not installed. 3:在Visual Studio中管理Nuget包中搜索CORS,我正在使用VS 2013.确保选中左窗格中的Online,并且可以看到Microsoft ASP.NET Web API 2.2跨源支持并安装(如果未安装) 。 If at all the same package is already installed to your Web API, then a right mark in green rounded circle would be visible against the package. 如果您的Web API已经安装了相同的软件包,则在软件包上可以看到绿色圆形圆圈中的右侧标记。

4: At the outset, we have mentioned that while implementing Account Membership, the error is seen. 4:首先,我们提到在实施帐户成员资格时,会看到错误。 Now to resolve the issue, add the following using statement to AccountController. 现在要解决此问题,请将以下using语句添加到AccountController。 The attribute can be applied at specific function level or for all like the following: 该属性可以应用于特定的功能级别,也可以应用于以下所有类别:

[EnableCors(origins: "*", headers: "*", methods: "*")]

The above attribute ideally should be placed just above [Authorize] attribute. 理想情况下,上述属性应放在[Authorize]属性的上方。

5: In order to apply CORS to all controllers in Web API, one can include the following as the first line in Register method in WebApiConfig.cs. 5:为了将CORS应用于Web API中的所有控制器,可以在WebApiConfig.cs中的Register方法中包含以下内容作为第一行。

public static void Register(HttpConfiguration config)
{
config.EnableCors();
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
......

6: While implementing Individual Authentication using Membership Database, the template in Visual Studio adds ApplicationOAuthProvider.cs file. 6:使用成员资格数据库实现个人身份验证时,Visual Studio中的模板添加了ApplicationOAuthProvider.cs文件。 In the file, there is one method that grants resource credentials. 在该文件中,有一种方法可以授予资源凭据。 The method name is: 方法名称是:

public override async Task GrantResourceOwnerCredentials
(OAuthGrantResourceOwnerCredentialsContext context)

In that method, one needs to check if some what like this is ever added. 在该方法中,需要检查是否添加了类似的内容。

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", 
new[] { "yourdomain:yourpostnumber" });

If that is there and the client tries to login, then the following error can be seen in Console tab 如果存在并且客户端尝试登录,则可以在“控制台”选项卡中看到以下错误

在此输入图像描述

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53005' is therefore not allowed access. The response had HTTP status code 500.

在此输入图像描述

This is because we have already enabled config.EnableCors(); 这是因为我们已经启用了config.EnableCors(); in WebApiConfig.cs and also try to add context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "yourdomain:yourpostnumber" }); 在WebApiConfig.cs中也尝试添加context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "yourdomain:yourpostnumber" });

So make sure to take off the context.OwinContext.Response.Headers.Add line from ApplicationOAuthProvider.cs file and give a try. 因此,请务必从ApplicationOAuthProvider.cs文件中取出context.OwinContext.Response.Headers.Add行并尝试一下。 No error would be visible. 没有错误可见。

Also for further reference please check CORS ISSUE 如需进一步参考,请查看CORS ISSUE

Hope it helps. 希望能帮助到你。

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

相关问题 CORS:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。 REACTJS, AXIOS - CORS: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. REACTJS, AXIOS 预检请求未通过访问控制检查:它没有 HTTP ok 状态 - Preflight request doesn't pass access control check: It does not have HTTP ok status 对预检请求的响应未通过访问控制检查(JavaScript) - Response to preflight request doesn't pass access control check (JavaScript) CORS-对预检请求的响应未通过访问控制检查 - CORS - Response to preflight request doesn't pass access control check 对预检请求的响应未通过 Angular 2 的访问控制检查 - Response to preflight request doesn't pass access control check with Angular 2 对预检请求的角度响应未通过访问控制检查 - Angular Response to preflight request doesn't pass access control check Javascript - 对预检请求的响应未通过访问控制检查 - Javascript - Response to preflight request doesn't pass access control check 对预检请求的响应未通过访问控制检查 - Response to preflight request doesn't pass access control check 对预检请求的响应未通过访问控制检查错误 - Response to preflight request doesn't pass access control check error 对预检请求的响应未通过NodeJS中的访问控制检查 - Response to preflight request doesn't pass access control check in NodeJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM