Asp.net 웹 API를 사용하는 AngularJS : XMLHttpRequest를 반환하는 $ http 게시물을로드 할 수 없음 : 프리 플라이트에 대한 응답에 잘못된 HTTP 상태 코드 405가 있습니다.

비 카스 반살

Asp.net 웹 API 서버를 사용하여 json을 POST하려고 $http하면 다음 오류가 반환됩니다.

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

그러나 동일한 요청을 만드는 $.ajax것은 작업 파일입니다.

$ HTTP 코드

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

$ .ajax 코드

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

asp.net 웹 API 코드 및 구성

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 컨트롤러

[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);
        }
    }
비 카스 반살

@Rakeschand 당신이 옳았 그것은 문제였다 고르

Cors

nu-get 명령 줄을 사용하여 프로젝트에 Cors를 설치했습니다.

Install-Package Microsoft.AspNet.WebApi.Cors

App_Start 폴더의 WebApiConfig.cs 파일에 다음 코드를 추가했습니다.

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

웹 구성에서 다음을 제거했습니다.

   <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가 작동하는 것처럼 작동하기 시작 $.ajax했습니다.

그러나 이러한 것들이 저를 혼란스럽게했습니다. 누구든지 정교하게 할 수 있다면

  1. $.ajax작동하고 $http작동하지 않았는지
  2. 나는 그 당시에했던 것과 똑같은 일을 cors했는데 web.configcors일을했지만 그렇지 web.config않았습니까?

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관