0
    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

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"

My Ajax Call:

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?

Ondrej Svejdar
  • 19,236
  • 4
  • 49
  • 77
Ram Prakash
  • 11
  • 1
  • 4
  • This looks like CORS issue. Browser when making request to different domain first issues "OPTION" request to see if it is ok - service then has to confirm the VERB/Domain/etc. is allowed - otherwise random guys form any page on internet can call your endpoint. Make sure to configure CORS in your MVC properly / when testing via postman go via OPTION request instead. – Ondrej Svejdar Apr 16 '19 at 10:07

1 Answers1

0

The reason for the above is referred to CORS (Cross Origin Resource Sharing)

there are several tips and tricks available in plural sites for 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.

<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.

If Internet Explorer 10 or 11 is used, then in Console Tab, the following error can be seen.

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

2: Remove the headers from the web.config mentioned above.

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. 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.

4: At the outset, we have mentioned that while implementing Account Membership, the error is seen. Now to resolve the issue, add the following using statement to 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.

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.

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. 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

enter image description here

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.

enter image description here

This is because we have already enabled config.EnableCors(); in WebApiConfig.cs and also try to add 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. No error would be visible.

Also for further reference please check CORS ISSUE

Hope it helps.

Mohit Verma
  • 4,531
  • 2
  • 8
  • 25