1

I am currently having an issue with my AngularJS and my .net WebAPI. I can successfully get content or objects through my WebAPI, however I am currently experiencing issues POSTING data.

The errors that I get when trying to post the content is as follows:

OPTIONS http://localhost:18130/api/Products XMLHttpRequest cannot load

http://localhost:18130/api/Products. Response for preflight has invalid HTTP status code 405

Bear in mind that when I try to post using Fiddler it works absolutely fine, no issues whatsoever.

The following is my AngularJS code I am using to post:

var data = { "Title": $scope.title, "Description": $scope.description };

$http.post(
    'http://localhost:18130/api/Products',
     JSON.stringify(data), {
         headers: {
             'Content-Type': 'application/json; charset=UTF-8'
          }
      }).success(function (data) {
          console.log(data);
      });

Could someone possibly direct me to correct direction? Both WebApi and the AngularJS app are in separate domains, is this a CORS issue? How do I go around to fix when posting.

Thank you in advance.

14
  • 1
    Try to disable WebDAV module in web.config Commented Mar 11, 2016 at 16:14
  • 1
    it may be installed on IIS. I will post example config from shared hosting we have similar issue on. Commented Mar 11, 2016 at 16:18
  • 1
    Definitely CORS, search around on the web to enable it for web api. It was an evolving process for a bit, so you'll see different approaches dependent on the age of the article, but here is a good starting point Commented Mar 11, 2016 at 16:20
  • 1
    You shouldn't have to call JSON.stringify(data). I believe Angular takes care of that for you. Commented Mar 11, 2016 at 16:24
  • 1
    sorry, didn't noticed the part about different domains. you can try to use package from this example provided above or from asp.net site (i suppose the used method is the same). Commented Mar 11, 2016 at 16:25

2 Answers 2

1

Depending on what template you used when creating your web api project, it may or may not use OWIN. Assuming that it is (if not, the other answer by scniro will be a betting starting point):

I had a similar issue when I was posting to web api from a js app. I installed Microsoft.Owin.Cors from nuget and in my Startup.cs I added:

    public void Configuration(IAppBuilder app) {
        app.UseCors(new CorsOptions {
            PolicyProvider = new CorsPolicyProvider {
                PolicyResolver = context => {
                    CorsPolicy result = new CorsPolicy {
                        AllowAnyHeader = true,
                        AllowAnyMethod = true,
                        AllowAnyOrigin = true,
                        SupportsCredentials = true
                    };                        
                    return Task.FromResult(result);
                }
            }
        });
    }

This will allow everything. In production you can change this to allow requests only from origins that you allow like this:

    public void Configuration(IAppBuilder app) {
        app.UseCors(new CorsOptions {
            PolicyProvider = new CorsPolicyProvider {
                PolicyResolver = context => {
                    CorsPolicy result = new CorsPolicy {
                        AllowAnyHeader = true,
                        AllowAnyMethod = true,
                        AllowAnyOrigin = false,
                        SupportsCredentials = true
                    };
                    result.Origins.Add(ConfigurationManager.AppSettings.Get("YourAllowedUrl"));
                    return Task.FromResult(result);
                }
            }
        });
    }

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

I should not be using OWIN for this
Ok no worries, I will leave this answer here in case anyone comes across this question and has had a similar issue when using web api with OWIN.
Hey Magrangs I have tried to install this and I no longer get the error I was getting, but no data is submitted! So when a debug every field appear to be null, any clues?
Okay, so turn out to be the answer for my question! I basically installed this package and added this code and it worked, plus had to do some additional changes. All good now. Thanks
@Jordan There be an issue with the data going up and it is not able to parse the json into a class. I use json.net, might be worth installing that and using that as your default serialiser. Alo I would need to see the post data going up in the console as it might be going up stringified.
1

@Jordan try to disable all hanlers and then readd in web.config:

<modules>
  <remove name="FormsAuthenticationModule" />
  <remove name="WebDAVModule" />
</modules>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

2 Comments

I have just tried this and no progress! I have not even got much custom code, not sure why it is not working
have you tried to post a JSON object like @Lex has advised? just like this: $http.post('http://localhost:18130/api/Products', data).then(successCallback, errorCallback)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.