Vikas Bansal
Vikas Bansal

Reputation: 11730

AngularJS With Asp.net Web API: $http post returning XMLHttpRequest cannot load: Response for preflight has invalid HTTP status code 405

When trying to POST json to Asp.net web API server using $http it's returning the following error

XMLHttpRequest cannot load http://localhost:62158/api/video/add.
Response for preflight has invalid HTTP status code 405

but making the same request from $.ajax is working file.

$HTTP Code

$http.post(url, data, config)
    .success(function (data, status, headers, config) {
        defered.resolve(data);
    })
    .error(function (data, status, header, config) {
        defered.reject(data);
    });

$.ajax Code

$.ajax({ type: "POST",
    url: url,
    data: newVideo,
    success: function (a) {
         debugger;
    },
    error: function (e) {
       debugger;
    },
    dataType: 'json'
});

asp.net web api code and configuration

web.config

<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" />
    </customHeaders>
</httpProtocol>

WebApiConfig

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );


    VideoLIbraryDb.Config.setconnection();

    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));


}

API controller

[RoutePrefix("api/video")]
    public class VideoController : ApiController
    {
        [Route("add")]
        [HttpPost]
        public HttpResponseMessage add([FromBody] db_videos newVideo)
        {
            HttpStatusCode statusCode = HttpStatusCode.NotFound;

            CommonResult result = new CommonResult() /// default
            {
                code = ResultCodes.retry.ToString(),
                message = "Not able to complete request. Retry."
            };

            if (newVideo.video_file_name == null)
                return Request.CreateResponse(statusCode, result);

            if (newVideo.video_file_name.Length < 1)
                return Request.CreateResponse(statusCode, result);


            if (newVideo.insert())
            {
                statusCode = HttpStatusCode.OK;
                result.code = ResultCodes.successfull.ToString();
                result.message = "Video is added";
            }

            return Request.CreateResponse(statusCode, result);
        }
    }

Upvotes: 11

Views: 11322

Answers (2)

Vikas Bansal
Vikas Bansal

Reputation: 11730

@Rakeschand you were right and it was the issue of cors

Cors

I installed Cors in my project using nu-get command line

Install-Package Microsoft.AspNet.WebApi.Cors

and added the follwoing code in WebApiConfig.cs file from App_Start folder.

var enableCorsAttribute = new EnableCorsAttribute("*",
                                               "Origin, Content-Type, Accept",
                                               "GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);

and removed the following from the web config

   <remove name="X-Powered-By" />
                    <add name="Access-Control-Allow-Origin" value="*" />
                    <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
                    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />

$http started working just like the $.ajax was working

but these things left me with some confusion. I would be great full if anyone can elaborate

  1. why the $.ajax was working and $http was not working
  2. I did the same thing by cors the I had done in web.config then why did cors worked but web.config didn't?

Upvotes: 20

Tiago Gouv&#234;a
Tiago Gouv&#234;a

Reputation: 16740

I think you must set the content-type on your ajax call:

contentType: 'application/x-www-form-urlencoded; charset=utf-8',

or

contentType: 'application/json; charset=utf-8',

Upvotes: 2

Related Questions