我正在开发一个网站,在该网站上我需要发布数据以创建一个记录。我的服务器端代码在不同的域上。我需要从该域调用该方法。我称呼该方法的Ajax代码为 -
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#create').click(function (e) {
var url = 'http://abc.in/api/api/Patient/Create';
$.ajax({
url: url,
crossDomain: true,
contentType: "application/json",
dataType: "json",
data: JSON.stringify(getData()),
type: 'POST',
success: function (result) {
},
error: function (result) {
}
});
});
});
</script>
</head>
和我的服务器端代码在global.asax中是 -
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "Create",
routeTemplate: "api/Patient/Create",
defaults: new { controller = "Patient", action = "Create" }
);
routes.MapHttpRoute(
name: "Update",
routeTemplate: "api/Patient/Update",
defaults: new { controller = "Patient", action = "Update" }
);
routes.MapHttpRoute(
name: "Get",
routeTemplate: "api/Patient/Get/{id}",
defaults: new { controller = "Patient", action = "Get" }
);
routes.MapHttpRoute(
name: "GetUploadDocumentListByPatient",
routeTemplate: "api/UploadFile/GetUploadDocumentListByPatient/{id}",
defaults: new { controller = "UploadFile", action = "GetUploadDocumentListByPatient" }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {controller="Patient", action = "GetTest", id = RouteParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
}
我的Corshandler如下 -
public class CorsHandler : DelegatingHandler
{
private const string Origin = "Origin";
private const string AccessControlRequestMethod = "Access-Control-Request-Method";
private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
try
{
IEnumerable<string> headers = request.Headers.GetValues(AccessControlRequestHeaders);
;
if (headers != null)
{
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{ response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
}
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
catch
{
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
}
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
return base.SendAsync(request, cancellationToken);
}
}
从不同域,即abc.in
获取记录时没有问题,它会使用ajax响应数据。但是当我尝试使用上述ajax调用数据发布数据时
XMLHttpRequest cannot load http://abc.in/api/api/Patient/Create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56139' is therefore not allowed access.
我想念什么吗?通过使用Google提供的高级REST客户端应用程序,成功创建了记录。我的ajax呼叫缺少什么吗?
umm,这可能会有所帮助单击我
function getJSON(url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
}