Search code examples
angularjsxmlhttprequesthttp-headershttp-status-code-405http-options-method

ANGULARJS: "XMLHttpRequest cannot load http://localhost:62259/Service1.svc/getAllUsers. Invalid HTTP status code 405"


So, this is the situation:

  1. I am developing a web app with AngularJS (client-side) and C# (server-side);
  2. I have already some web services running well, with no problems (gelAllUsers, getOrderDetails, etc etc);
  3. After I implement the authentication code, the web services stop working. Here are the errors messages:

  4. I realized then that the problem is due to every code lines with "$http.defaults.headers.common.Authorization = ..."

  5. After some search, I know I may need to do something which allows the Authorization header.

But what? And how?And where?


Solution

  • I found a solution, and it works thanks to an article in CodeProject. As I am novice in web developing, here is the detailed procedure I had to follow in order to perform it successfully:

    1. Understand why this problem exists and that all is needed is to enable CORS in WCF:

    2. As I am using Visual Studio to develop my WCF Web Services, in order to create the file Global.asax, I had to: * In Solution Explorer, right-click in the project name -> Add -> New Item... * in the left menu, Web -> General and the select Global Application Class * write this code:

      protected void Application_BeginRequest(object sender, EventArgs e)

    {

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
    

    }

    1. Note that, in this case, it is needed to add 'Authorization' in

      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");

    2. delete similar stuff you might have in web.config or else you will have a conflict due to redundant data.

    I thing I said everything.