ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

前端 未结 19 1906
Happy的楠姐
Happy的楠姐 2020-11-22 05:16

I recently upgraded from Visual Studio 2010 to the Visual Studio 2012 RC. The installer also installs IIS 8 Express which Visual Studio now uses as the default web server.

19条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:51

    Enable CORS (nice and neat)

    1.Add CORS nuget package

    Install-Package microsoft.aspnet.webapi.cors
    

    2.in the WebApiConfig.cs file to Register method add bellow code :

    config.EnableCors();
    

    ex:
    using System.Web.Http;

    namespace test
    {
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
    
    
            config.EnableCors(); //add this**************************
    
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );           
        }
    }
    }
    

    3.Add bellow code into namespace of the controller include get,post,delete,put or any http method

    [EnableCors(origins: "The address from which the request comes", headers: "*", methods: "*")]
    

    ex:

    using System.Web.Http.Cors;//add this******************************
    namespace Test.Controllers
    {
    [EnableCors(origins: "http://localhost:53681/HTML/Restaurant.html", headers: "*", methods: "*")]
    public class RestaurantController : ApiController
    {
        protected TestBusinessLayer DevTestBLL = new TestBusinessLayer();
    
        public List GET()
        {
            return DevTestBLL.GetRestaurant();
        }
    
        public List DELETE(int id)
        {
            return DevTestBLL.DeleteRestaurant(id);
        }       
    }
    }
    

    reference :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

提交回复
热议问题