我正在尝试将跨域ajax帖子实现到我的webApi项目中.我没有遇到什么麻烦:
1.在改变我的webapi动作之前,我总是遇到204错误
public void submit(Submission model)
Run Code Online (Sandbox Code Playgroud)
至
public bool submit(Submission model)
Run Code Online (Sandbox Code Playgroud)
不知道为什么,但现在我得到200 OK状态
2.仍然是我的ajax发射错误回调.
很久以前,我通过添加解决了跨域发布的这种错误
HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
Run Code Online (Sandbox Code Playgroud)
到我的控制器.但现在在webApi我是固有的: ApiController ,这个技巧不起作用.显示我Error an object reference is required for the non-static field, method, or property"System.Web.HttpContext.Response.get"
试图发布的编译器,dataType: 'JSONP'但我得到了null模型.
这里有Javascript请求:
var model = {
"type": $("#model-type").val(),
"subject": $("#subject-text").val(),
"body": $("#body-text").val()
};
$.ajax({
type: "POST",
dataType: 'JSONP',
url: $("#submit-url").val(),
data: model,
success: function () {
alert("Succesfully submitted");
},
error: function () {
alert("Error...");
}
});
我做错了什么? …
我遇到了麻烦,制作了Ninject和WebAPI.All合作.我将更加具体:
首先,我玩了WebApi.All包,看起来它对我来说很好.
第二,我加入RegisterRoutes的Global.asax下一行:
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
Run Code Online (Sandbox Code Playgroud)
所以最终的结果是:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
Run Code Online (Sandbox Code Playgroud)
一切似乎都很好,但是当我试图将用户重定向到特定的操作时,例如:
return RedirectToAction("Index", "Home");
Run Code Online (Sandbox Code Playgroud)
localhost:789/api/contacts?action=Index&controller=Home
是不好的.我划了一条线RegisterRoute,现在它看起来像:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new …Run Code Online (Sandbox Code Playgroud)