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
했습니다.
그러나 이러한 것들이 저를 혼란스럽게했습니다. 누구든지 정교하게 할 수 있다면
$.ajax
작동하고 $http
작동하지 않았는지cors
했는데 web.config
왜 cors
일을했지만 그렇지 web.config
않았습니까?이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다