MVC 4.5的Web API请求不工作 [英] MVC 4.5 Web API request is not working

查看:190
本文介绍了MVC 4.5的Web API请求不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设计.NET中的MVC 4.5的Web API。 HTTP请求必须从jQuery的AJAX调用的。
使得调用(POST)后,我得到了控制台下面的错误。谁能帮我找出我在做什么错了?

 选项的http://192.168.xx.xx:1245 / API /值405(不允许的方法)的jQuery-1.7.1.min.js:4
OPTIONS HTTP://192.168.xx.xx:1245 / API /值无效HTTP状态code 405的j​​Query-1.7.1.min.js:4
XMLHtt prequest无法加载的http://192.168.xx.xx:1245 / API /值。无效的HTTP状态code 405


解决方案

您违反 同源策略限制 通过使这是默认不允许的跨域AJAX调用。您可能需要在Web API端启用CORS:的http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

 安装封装Microsoft.AspNet.WebApi.Cors -project YourWebApiProject

然后在你的配置只需启用CORS:

 公共静态类WebApiConfig
{
    公共静态无效的注册(HttpConfiguration配置)
    {
        config.EnableCors();        config.Routes.MapHttpRoute(
            名称:DefaultApi
            routeTemplate:API / {}控制器/(编号),
            默认:新{ID = RouteParameter.Optional}
        );
    }
}

这将使你从支持CORS的浏览器做跨域AJAX请求到你的Web API。

I have designed a MVC 4.5 Web API in .Net. HTTP request has to be made from Jquery AJAX Call. After making the call(POST) I get the following error in console. Can anyone help me to identify what I am doing wrong?

    OPTIONS http://192.168.xx.xx:1245/api/values 405 (Method Not Allowed) jquery-1.7.1.min.js:4
OPTIONS http://192.168.xx.xx:1245/api/values Invalid HTTP status code 405 jquery-1.7.1.min.js:4
XMLHttpRequest cannot load http://192.168.xx.xx:1245/api/values. Invalid HTTP status code 405 

解决方案

You are violating the same origin policy restriction by making a cross domain AJAX call which is not allowed by default. You might need to enable CORS on the Web API side: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Install-Package Microsoft.AspNet.WebApi.Cors -project YourWebApiProject

and then in your config simply enable CORS:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

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

This will enable you to make cross domain AJAX requests to your Web API from browsers that support CORS.

这篇关于MVC 4.5的Web API请求不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆