当前位置:  开发笔记 > 编程语言 > 正文

MVC-Web API:不允许使用405方法

如何解决《MVC-WebAPI:不允许使用405方法》经验,为你挑选了2个好方法。

所以,我陷入了一种奇怪的行为,也就是说,我能够使用Postman (plugin of chrome)或使用发送(或POST)数据RESTClient(extension of Firefox),

在此输入图像描述

但是无法从我位于项目之外的html文件中发送它.当我在chrome中打开html时显示以下错误:

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

我无法弄清楚为什么会这样.以下是详细信息,您可能需要帮我解决我的错误:

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 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(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 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 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的:



    
        TODO supply a title
        
        -->
        
    
    
        
    

Web.config文件:




  
    
    

Chintan Soni.. 25

好.在@martennis回答的帮助下解决了这个问题,但稍微纠正了一下.

每件事情都很完美,只需要注意,我们需要在Package Manager Console中输入以下命令:

Install-Package Microsoft.AspNet.WebApi.Cors –IncludePrerelease

而不是@martennis提供的链接中显示的那个,之后,我的WebApiConfig.cs更新如下:

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

namespace WebApiRESTfulwithJSON
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

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

因此,解决了问题...... !!!

现在,我将能够从任何地方使用我的Web服务,从移动应用程序,Web应用程序或桌面应用程序调用它.

对于,如何从头开始创建它们,我写了我的第一篇博客(...虽然是Android开发人员,但从未尝试过为Android编写博客:-P无论如何......)

链接:http://programmingwithease.wordpress.com/2014/06/18/learning-asp-net-web-api-2-using-c/



1> Chintan Soni..:

好.在@martennis回答的帮助下解决了这个问题,但稍微纠正了一下.

每件事情都很完美,只需要注意,我们需要在Package Manager Console中输入以下命令:

Install-Package Microsoft.AspNet.WebApi.Cors –IncludePrerelease

而不是@martennis提供的链接中显示的那个,之后,我的WebApiConfig.cs更新如下:

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

namespace WebApiRESTfulwithJSON
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

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

因此,解决了问题...... !!!

现在,我将能够从任何地方使用我的Web服务,从移动应用程序,Web应用程序或桌面应用程序调用它.

对于,如何从头开始创建它们,我写了我的第一篇博客(...虽然是Android开发人员,但从未尝试过为Android编写博客:-P无论如何......)

链接:http://programmingwithease.wordpress.com/2014/06/18/learning-asp-net-web-api-2-using-c/



2> martennis..:

WebApi可能会阻止CORS请求.要在WebApi上启用CORS,请使用Microsoft.AspNet.WebApi.Cors包.有关详细信息,请查看http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有