2
votes

I am trying to call a WCF service Method using Http POST Request from another Project , it allows GET request but when I try for POST request it is showing "Method not allowed".

When i tried it shows this error in my Console:

Access to XMLHttpRequest at 'http://localhost:7280/api/values/24' from origin 'http://localhost:6538' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Web API: Method:

[WebInvoke(UriTemplate = "/values", Method = "POST", ResponseFormat = WebMessageFormat.Json), CorsEnabled]
        void AddValue(string value);

Method Implementation

public void AddValue(string value)
        {
            string id = nextId.ToString();
            nextId++;
            allValues.Add(id, value);
            string location = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + "/" + id;
            WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(new Uri(location));
        }

Client Application:

$("#post").click(function () {
            var data = "\"" + $("#value").val() + "\"";
            $.ajax({
                url: valuesAddress,
                type: "POST",
                contentType: "application/json",
                data: data,
                success: function (result) {
                    $("#result").text(result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#result").text(textStatus);
                }
            });
        });

I followed https://code.msdn.microsoft.com/Implementing-CORS-support-c1f9cd4b/view/SourceCode#content I created web API and client Application as different projects. Please help to solve this issue.

2
For cors configuration in wcf , you could try to add cors headers and allow option method in Application_BeginRequest in global.asax , please refer to https://www.codeproject.com/Articles/845474/Enabling-CORS-in-WCFAckelry Xu
I am trying to call a WCF service Method using Http POST Request from another Project .I tried with the solution in codeproject.com/Articles/845474/Enabling-CORS-in-WCF, but didn't work . Can you please suggest any other solutions.TechportSolutions

2 Answers

1
votes

You have enabled the Cors attribute, when you look into the documentation MSDN provides you'll see that you have to provide the attribute above a class or method. The code below allows all methods in the class to be called cross domain.

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class Service1 : IService1
{
  // Details omitted
}

The code below enables cors for the GetAllStudents method.

public class Service1 : IService1
{
  [EnableCors(origins: "*", headers: "*", methods: "*")]
  List<string> GetAllStudents()
  {
    // Details omitted
  }
}
1
votes

I was having a problem with CORS myself, here is how I did it in asp.net (same judging by your tags):

  • I have installed the following NuGet package:

    Install-Package Microsoft.AspNet.WebApi.Cors

  • Then in your WebApiConfig file:
        public static void Register(HttpConfiguration config)
        {
            EnableCorsAttribute cors = new 
                 EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            AddRoutes(config);
        }

You have already done this step, just move the EnableCors(cors) method above the AddRoutes(config);

  • Lastly, you put the following attribute above SaveWithPost:
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]

Note: If you keep getting this error:

OPTIONS http://localhost/Service1.svc/saveWithPost/WithParameter 405 (Method Not Allowed) Access to XMLHttpRequest at 'http://localhost/Service1.svc/saveWithPost/WithParameter' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Read here the official documentation of Microsoft. The link brings you under How Cors Work, where you can read more about preflight requests. Shortly, the browser sends an additional request, before the actual request. Read more here.

Another side note: Check if you are not blocking the OPTIONS request. For instance, some companies use software for security, networking and storage products based on network appliances and cloud services, which FILTER all the upcoming requests to their own server, which may sometime lead to this. (not likely)

Hope this helps,

Cheers