MVC-Web API: 405 method not allowed

前端 未结 4 599
悲&欢浪女
悲&欢浪女 2020-11-29 08:51

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)<

相关标签:
4条回答
  • 2020-11-29 09:16

    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

    0 讨论(0)
  • 2020-11-29 09:17

    Removing "using System.Web.MVC" from controller class solved this problem for me.

    0 讨论(0)
  • 2020-11-29 09:27

    No need webconfig, all you need is to add:

      services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                }));
    
    0 讨论(0)
  • 2020-11-29 09:29

    Ok. Solved the problem with the help of @martennis answer, but with a little correction.

    Every things perfect, just to take care is, we need to enter following command in Package Manager Console:

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

    Instead of the one shown in the link provided by, @martennis, and after that, my WebApiConfig.cs was updated as follows:

    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 }
                );
            }
        }
    }
    

    Hence, solved the problem...!!!

    Now, I will able to use my web services from anywhere, calling it from mobile applications, web applications or desktop applications.

    For, how to create them from scratch, I wrote my first blog on this (...inspite of being android developer, never tried to write a blog for Android :-P Anyways...)

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

    0 讨论(0)
提交回复
热议问题