0

Hi I am developing web api2 project. I hosted application in server 192.168.0.213 and I am trying to access the methods as below.

 this.getSubs = function () {
        var url = 'http://192.168.0.213:7777/api/User_Creation/';
        return $http.get(url).then(function (response) {
            return response.data;
        });
    }

Above function returns the data with no issues. For example my below methods with verbs such as PUT,DELETE and POST not working.

this.saveSubscriber = function (sub) {
        return $http({
            method: 'post',
            data: JSON.stringify(sub),
            url: 'http://192.168.0.213:7777/api/User_Creation/',
            contentType: "application/json"
        });
    }

I tried many ways still did not worked any methods. Currently i have below code in web.config file.

 <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,DELETE" />
      </customHeaders>

Also i have below line of code in webapiconfig.cs file.

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

Also i have below line of code in controller. Still does not working anything.

  [EnableCors(origins: "http://192.168.0.213:7777", headers: "*", methods: "*")]

Also i commented . I tried all the ways only GET verb is working fine. My insert update delete operations are not working. May I know where i am doing things wrong? May i get some help on this as i tried my best still no luck.. Thank you all.

Niranjan Godbole
  • 2,135
  • 7
  • 43
  • 90
  • It's probably doing a preflight request. See https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api and http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors I'm having a similar problem with MVC, I'm not sure what the issue is. – Mahendran Nadesan Jan 13 '17 at 08:51
  • Thank you. I am getting below error. MLHttpRequest cannot load http://192.168.0.54:8099/api/User_Creation/41. Response for preflight has invalid HTTP status code 405 – Niranjan Godbole Jan 13 '17 at 08:53
  • So, I believe there's an OPTION verb that gets sent. One potential way around it is to not send `application/json` as your type, as per http://stackoverflow.com/a/22968724/2953322 – Mahendran Nadesan Jan 13 '17 at 08:54

2 Answers2

1

You should have [EnableCors(origins: "http://192.168.0.54", headers: "*", methods: "*")] in other words, your EnableCors should specify the client that attempts to connect, not the server itself

Felix
  • 9,248
  • 10
  • 57
  • 89
  • Whenever i make below delete request through postman http://192.168.0.213:7777/api/User_Creation/41 it works fine. Seems to be strange. In postman below things i can see Access-Control-Allow-Methods →POST,GET,PUT,DELETE Access-Control-Allow-Origin →* May i know whats wrong here? – Niranjan Godbole Jan 13 '17 at 09:10
  • Running through Postman is irrelevant, since it doesn't involve CORS. You didn't mention whether you also enabled CORS in `Register()`. Take a look here: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api for many more details and see how your code is different from the reference implementation – Felix Jan 13 '17 at 09:14
1

try wigh something like this: (for me work perfectly):

Startup.cs file: (install Microsoft.Owin.Cors nuget packages before)

using Goocity.API;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup("API", typeof(Goocity.API.Startup))]

namespace Goocity.API
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            #region TO UNCOMMENT WHEN IS IN PRODUCTION
            //var corsPolicy = new CorsPolicy
            //{
            //    AllowAnyMethod = true,
            //    AllowAnyHeader = true,
            //    SupportsCredentials = true,
            //    Origins = { "http://www.mysite.it" }
            //};

            //app.UseCors(new CorsOptions
            //{
            //    PolicyProvider = new CorsPolicyProvider
            //    {
            //        PolicyResolver = context => Task.FromResult(corsPolicy)
            //    }
            //});
            #endregion TO UNCOMMENT WHEN IS IN PRODUCTION

            app.UseCors(CorsOptions.AllowAll);
            ConfigureAuth(app);

        }
    }
}

then your webconfig: (in the system.webserver section)

<system.webServer>
    <httpProtocol>
      <customHeaders>

        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token, Cache-Control" />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
    <!--<rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
        </rule>

      </rules>
    </rewrite>-->

    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

  </system.webServer>

Hope it help you!!...

federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24