MVC的Web API:405方法不被允许 [英] MVC-Web API: 405 method not allowed

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

问题描述

所以,我被困在一个奇怪的现象,那就是,我能送(或POST)使用数据邮差(铬的插件)或使用 RESTClient实现(火狐扩展)

但不能从位于项目之外我的HTML文件发送。当我在Chrome中打开HTML它显示了以下错误:

 选项的http://本地主机:1176 / API /用户/ 405(不允许的方法)
XMLHtt prequest无法加载的http://本地主机:1176 / API /用户/。无效的HTTP状态code 405

我不能够做出来的为什么会这样。以下是详细信息,您可能需要帮我解决我的错误:

UserController.cs:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Net;
使用System.Net.Http;
使用System.Web.Http;
使用WebAPIv2.Models;命名空间WebAPIv2.Controllers
{
    公共类UserController的:ApiController
    {
        静态IUserRepository userRepository =新UserRepository();        [HTTPGET]
        公开名单< TableUser> GetAllUsers()
        {
            返回userRepository.GetAll();
        }        [HTTPGET]
        公众的Htt presponseMessage的getUser(INT ID)
        {
            TableUser用户= userRepository.Get(ID);
            如果(用户== NULL)
            {
                返回Request.CreateErrorResponse(的HTTPStatus code.NotFound,用户未找到为给定的ID);
            }            其他
            {
                返回Request.CreateResponse(的HTTPStatus code.OK,用户);
            }
        }        [HttpPost]
        公众的Htt presponseMessage PostUser(TableUser用户)
        {
            用户= userRepository.Add(用户);
            VAR响应= Request.CreateResponse< TableUser>(的HTTPStatus code.Created,用户);
            字符串URI = Url.Link(DefaultApi,新{ID = user.UserId});
            response.Headers.Location =新的URI(URI);
            返回响应;
        }        [HttpPut]
        公众的Htt presponseMessage PutUser(INT ID,TableUser用户)
        {
            user.UserId = ID;
            如果(!userRepository.Update(用户))
            {
                返回Request.CreateErrorResponse(的HTTPStatus code.NotFound,无法更新给定ID的用户);
            }
            其他
            {
                返回Request.CreateResponse(的HTTPStatus code.OK);
            }
        }        [HttpDelete]
        公众的Htt presponseMessage DeleteProduct(INT ID)
        {
            userRepository.Remove(ID);
            返回新的Htt presponseMessage(的HTTPStatus code.NoContent);
        }
    }
}

User.cs:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;命名空间WebAPIv2.Models
{
    公共类用户
    {
        公众诠释用户ID {搞定;组; }
        公共字符串用户名{获得;组; }
        公共字符串密码{搞定;组; }
        公共字符串名字{获得;组; }
        公共字符串名字{获得;组; }
        公共字符串电子邮件{获得;组; }
    }
}

IUserRepository.cs:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Threading.Tasks;命名空间WebAPIv2.Models
{
    接口IUserRepository
    {
        清单< TableUser>得到所有();
        TableUser获取(INT ID);
        TableUser添加(TableUser用户);
        无效删除(INT ID);
        布尔更新(TableUser用户);
    }
}

UserRepository.cs:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;命名空间WebAPIv2.Models
{
    公共类UserRepository:IUserRepository
    {
        MastarsFriendsMVCDatabaseEntities userEntities;        公共UserRepository()
        {
            userEntities =新MastarsFriendsMVCDatabaseEntities();
        }        公开名单< TableUser>得到所有()
        {
            //抛出新NotImplementedException();            返回userEntities.TableUsers.ToList();
        }        公共TableUser获取(INT ID)
        {
            //抛出新NotImplementedException();            VAR用户= userEntities.TableUsers.Where(X => x.UserId == ID);
            如果(users.Count()大于0)
            {
                返回users.Single();
            }
            其他
            {
                返回null;
            }
        }        公共TableUser添加(TableUser用户)
        {
            //抛出新NotImplementedException();            如果(用户== NULL)
            {
                抛出新的ArgumentNullException(项目);
            }
            userEntities.TableUsers.Add(用户);
            userEntities.SaveChanges();
            返回用户;
        }        公共无效删除(INT ID)
        {
            //抛出新NotImplementedException();            TableUser用户=获取(ID);
            如果(用户!= NULL)
            {
                userEntities.TableUsers.Remove(用户);
                userEntities.SaveChanges();
            }
        }        公共BOOL更新(TableUser用户)
        {
            //抛出新NotImplementedException();            如果(用户== NULL)
            {
                抛出新的ArgumentNullException(学生);
            }            TableUser userInDB = GET(user.UserId);            如果(userInDB == NULL)
            {
                返回false;
            }            userEntities.TableUsers.Remove(userInDB);
            userEntities.SaveChanges();            userEntities.TableUsers.Add(用户);
            userEntities.SaveChanges();            返回true;
        }
    }
}

WebApiConfig.cs:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Net.Http.Headers;
使用System.Web.Http;命名空间WebAPIv2
{
    公共静态类WebApiConfig
    {
        公共静态无效的注册(HttpConfiguration配置)
        {
            //网页API的配置和服务            //网页API路线
            config.MapHttpAttributeRoutes();
            //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(text / html的));
            config.Routes.MapHttpRoute(
                名称:DefaultApi
                routeTemplate:API / {}控制器/(编号),
                默认:新{ID = RouteParameter.Optional}
            );
        }
    }
}

index.html的:

 <!DOCTYPE HTML>
< HTML和GT;
    < HEAD>
        <标题> TODO提供标题< /标题>
        <间的charset =UTF-8>
        < META NAME =视口CONTENT =WIDTH =设备宽度,初始规模= 1.0>        !&所述; - &下; SCRIPT SRC =HTTP://$c$c.jquery.com/jquery-1.9.1.min.js>&下; /脚本&GT - →;
        &所述; SCRIPT SRC =HTTP://$c$c.jquery.com/jquery-2.1.0.min.js>&下; /脚本>
    < /头>
    <身体GT;
        <脚本>
            $(文件)。就绪(函数(){
// jQuery.support.cors = TRUE;
// $阿贾克斯({
// URL:HTTP://本地主机:1176 / API /用户/ 1
//头:{接受:应用/ JSON},
//类型:GET,
//成功:功能(数据){
//警报(JSON.stringify(数据));
//},
//错误:函数(){
//警报(错误);
//}
//});
//});                VAR用户= {
                    用户名:笛莎
                    密码:disha123
                    姓:笛莎
                    名字:沃拉
                    电子邮件:disha@pixielit.com
                };                $阿贾克斯({
                    网址:的http://本地主机:1176 / API /用户/',
                    输入:POST,
                    数据:JSON.stringify(用户)
                    跨域:真实,
                    标题:{接受:应用/ JSON,内容类型:应用/ JSON},
                    成功:功能(数据){
                        警报(用户添加成功);
                    },
                    错误:函数(){
                        警报(用户没有添加');
                    }
                });
            });
        < / SCRIPT>
    < /身体GT;
< / HTML>

的Web.config:

 <?XML版本=1.0编码=UTF-8&GT?;
<! -
  有关如何配置ASP.NET应用程序的更多信息,请访问:
  http://go.microsoft.com/fwlink/?LinkId=301879
   - >
<结构>
  < configSections>
    <! - 有关Entity Framework的配置的详细信息,请访问http://go.microsoft.com/fwlink/?LinkID=237468 - >
    <节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本5.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/>
  < / configSections>
  <&的appSettings GT;< /的appSettings>
  <&的System.Web GT;
    <编译调试=真targetFramework =4.5>
      <&集会GT;
        <添加组件=System.Data.Entity的,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089/>
      < /组件>
    < /编译>
    <的httpRuntime targetFramework =4.5/>
  < /system.web>
  < system.webServer>
    <验证validateIntegratedModeConfiguration =FALSE/>
    <模块runAllManagedModulesForAllRequests =真正的>
      <清除NAME =WebDAVModule/>
    < /模块>
    < httpProtocol>
      < customHeaders>
        <添加名称=访问控制允许来源VALUE =*/>
        <添加名称=访问控制请求报头:值=*/>
        <添加名称=访问控制请求法:值=*/>
        <添加名称=访问控制允许的方法VALUE =*/>
        <! - <添加名称=允许值=*/> - >
      < / customHeaders>
    < / httpProtocol>
    <&处理GT;
      <清除NAME =WebDAV的/>
      <清除NAME =ExtensionlessUrlHandler - 集成 - 4.0/>
      <清除NAME =OPTIONSVerbHandler/>
      <清除NAME =TRACEVerbHandler/>
      <添加名称=ExtensionlessUrlHandler - 集成 - 4.0PATH =*。动词=*类型=System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
    < /处理器>
    < directoryBrowse启用=真/>
  < /system.webServer>
  <&的EntityFramework GT;
    < defaultConnectionFactory TYPE =System.Data.Entity.Infrastructure.LocalDbConnectionFactory,的EntityFramework>
      <&参数GT;
        <参数值=11.0/>
      < /参数>
    < / defaultConnectionFactory>
  < /&的EntityFramework GT;
  <&是connectionStrings GT;
    <添加名称=MastarsFriendsMVCDatabaseEntities connectionString=\"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider连接字符串=安培; QUOT;数据源= WIN-WWU3DMLR6PX \\ PIXIELIT;初始目录= MastarsFriendsMVCDatabase;坚持安全信息= TRUE;用户ID = SA;密码= sa_12345; MultipleActiveResultSets = TRUE;应用=的EntityFramework和放大器; QUOT;的providerName = System.Data.EntityClient/>
  < /&是connectionStrings GT;
< /结构>


解决方案

的WebAPI可能阻止CORS请求。要启用的WebAPI CORS,使用Microsoft.AspNet.WebApi.Cors包。欲知详情,请查看<一个href=\"http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api\">http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

So, I am stuck in a strange behavior, that is, I am able to send(or POST) data using Postman (plugin of chrome) or using RESTClient(extension of Firefox),

but not able to send it from my html file which lies outside the project. It shows following error when i open the html in chrome:

OPTIONS http://localhost:1176/api/user/ 405 (Method Not Allowed)
XMLHttpRequest cannot load http://localhost:1176/api/user/. Invalid HTTP status code 405 

I am not able to make out why is this happening. Following are the details, you might need to help me solve my error:

UserController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPIv2.Models;

namespace WebAPIv2.Controllers
{
    public class UserController : ApiController
    {
        static IUserRepository userRepository = new UserRepository();

        [HttpGet]
        public List<TableUser> GetAllUsers()
        {
            return userRepository.GetAll();
        }

        [HttpGet]
        public HttpResponseMessage GetUser(int id)
        {
            TableUser user = userRepository.Get(id);
            if (user == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User Not found for the Given ID");
            }

            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, user);
            }
        }

        [HttpPost]
        public HttpResponseMessage PostUser(TableUser user)
        {
            user = userRepository.Add(user);
            var response = Request.CreateResponse<TableUser>(HttpStatusCode.Created, user);
            string uri = Url.Link("DefaultApi", new { id = user.UserId });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        [HttpPut]
        public HttpResponseMessage PutUser(int id, TableUser user)
        {
            user.UserId = id;
            if (!userRepository.Update(user))
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Unable to Update the User for the Given ID");
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }

        [HttpDelete]
        public HttpResponseMessage DeleteProduct(int id)
        {
            userRepository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}

User.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPIv2.Models
{
    public class User
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

IUserRepository.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebAPIv2.Models
{
    interface IUserRepository
    {
        List<TableUser> GetAll();
        TableUser Get(int id);
        TableUser Add(TableUser user);
        void Remove(int id);
        bool Update(TableUser user);
    }
}

UserRepository.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPIv2.Models
{
    public class UserRepository : IUserRepository
    {
        MastarsFriendsMVCDatabaseEntities userEntities;

        public UserRepository()
        {
            userEntities = new MastarsFriendsMVCDatabaseEntities();
        }

        public List<TableUser> GetAll()
        {
            //throw new NotImplementedException();

            return userEntities.TableUsers.ToList();
        }

        public TableUser Get(int id)
        {
            //throw new NotImplementedException();

            var users = userEntities.TableUsers.Where(x => x.UserId == id);
            if (users.Count() > 0)
            {
                return users.Single();
            }
            else
            {
                return null;
            }
        }

        public TableUser Add(TableUser user)
        {
            //throw new NotImplementedException();

            if (user == null)
            {
                throw new ArgumentNullException("item");
            }
            userEntities.TableUsers.Add(user);
            userEntities.SaveChanges();
            return user;
        }

        public void Remove(int id)
        {
            //throw new NotImplementedException();

            TableUser user = Get(id);
            if (user != null)
            {
                userEntities.TableUsers.Remove(user);
                userEntities.SaveChanges();
            }
        }

        public bool Update(TableUser user)
        {
            //throw new NotImplementedException();

            if (user == null)
            {
                throw new ArgumentNullException("student");
            }

            TableUser userInDB = Get(user.UserId);

            if (userInDB == null)
            {
                return false;
            }

            userEntities.TableUsers.Remove(userInDB);
            userEntities.SaveChanges();

            userEntities.TableUsers.Add(user);
            userEntities.SaveChanges();

            return true;
        }
    }
}

WebApiConfig.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;

namespace WebAPIv2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
        <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    </head>
    <body>
        <script>
            $(document).ready(function() {
//                jQuery.support.cors = true;
//                $.ajax({
//                    url: "http://localhost:1176/api/user/1",
//                    headers: {"Accept": "application/json"},
//                    type: "GET",
//                    success: function(data) {
//                        alert(JSON.stringify(data));
//                    },
//                    error: function() {
//                        alert("Error");
//                    }
//                });
//            });

                var user = {
                    UserName: "Disha",
                    Password: "disha123",
                    FirstName: "Disha",
                    LastName: "Vora",
                    Email: "disha@pixielit.com"
                };

                $.ajax({
                    url: 'http://localhost:1176/api/user/',
                    type: 'POST',
                    data: JSON.stringify(user),
                    crossDomain: true,
                    headers: {"Accept":"application/json" , "Content-Type":"application/json"},
                    success: function(data) {
                        alert('User added Successfully');
                    },
                    error: function() {
                        alert('User not Added');
                    }
                });
            });
        </script>
    </body>
</html>

Web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings></appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Request-Headers:" value="*" />
        <add name="Access-Control-Request-Method:" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
        <!--<add name="Allow" value="*"/>-->
      </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <connectionStrings>
    <add name="MastarsFriendsMVCDatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=WIN-WWU3DMLR6PX\PIXIELIT;initial catalog=MastarsFriendsMVCDatabase;persist security info=True;user id=sa;password=sa_12345;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

解决方案

WebApi probably blocks the CORS request. To enable CORS on WebApi, use the Microsoft.AspNet.WebApi.Cors package. For further details, check http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

这篇关于MVC的Web API:405方法不被允许的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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