简体   繁体   English

WebApi Post 方法总是返回“请求的资源不支持 http 方法 'GET'。” 状态:405 方法不允许

[英]WebApi Post Methods always Returns “The requested resource does not support http method 'GET'.” Status: 405 Method Not Allowed

I Created a simple web api service to GET & POST User Data .我创建了一个简单的 web api 服务来获取和发布用户数据

Every thing is well at Localhost. Localhost 的一切都很好。 But when i host Service at server, Get Method is working fine when i call it from PostMan/Browser.但是当我在服务器上托管 Service 时,当我从 PostMan/Browser 调用它时,Get Method 工作正常。 But Post Methods always returns "The requested resource does not support http method 'GET'."但是 Post Methods 总是返回“请求的资源不支持 http 方法 'GET'。” Status: 405 Method Not Allowed .状态:405 方法不允许

One thing i got Confused here ie I requested a POST Call, but status message shows me 'GET' error.我在这里感到困惑的一件事,即我请求了一个 POST 呼叫,但状态消息显示我“GET”错误。 Why it should be?为什么应该这样? If it is CORS problem?如果是CORS问题? I tried CORS enable too with various scenarios/aspects by searching answers on internet at Application level(Web.Config as well Nuget Package Manager Cors).我通过在应用程序级别(Web.Config 以及 Nuget 包管理器 Cors)在 Internet 上搜索答案,尝试在各种场景/方面启用 CORS。 Still getting 405 Method Not Allowed.仍然得到 405 Method Not Allowed。 Below pasted my API Code:下面粘贴了我的 API 代码:

Controller NameSpaces:控制器命名空间:

  using MySql.Data.MySqlClient;
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Web.Http;
  using System.Web.Http.Cors;

Controller控制器

  public class UsersController : ApiController
  {
    [Route("api/Users/GetUsers/{UserId}")]
    [HttpGet]
    public IEnumerable<User> GetUsers(int UserId)
    {
        try
        {
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("GetUsers");
            cmd.Parameters.AddWithValue("aUserId", UserId);
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            // Did Some Stuff and Returns Model;
            return userlist;
        }
        catch(Exception ex)
        {
            // Written Error Log & Returns Empty Model;
        }
    }

    [Route("api/Users/SaveUser")]
    [HttpPost]
    public IEnumerable<User> SaveUser([FromBody]dynamic request)
    {
        try
        {
            string UserName = request.Param_Name;
            string Email = request.Param_Email;
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("UserSave");
            cmd.Parameters.AddWithValue("aUserName", UserName);
            cmd.Parameters.AddWithValue("aEmail", Email);
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            UserAuthenticate userdata;
            // Did Some Stuff and returns UserModel;
            return userlist;
        }
        catch(Exception Ex)
        {
            // Written Error Log & Returns Empty Model with Error Message;
        }
    }

    [Route("api/Users/SaveUserModel")]
    [HttpPost]
    public IEnumerable<User> SaveUserModel([FromBody]User request)
    {
        try
        {
            string Param_UserName = request._UserName;
            string Param_Email = request._Email;
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("UserSave");
            cmd.Parameters.AddWithValue("aUserName", Param_UserName);
            cmd.Parameters.AddWithValue("aEmail", Param_Email );
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            UserAuthenticate userdata;
            // Did Some Stuff and returns UserModel;
            return userlist;
        }
        catch(Exception Ex)
        {
            // Written Error Log & Returns Empty Model with Error Message;
        }
    }
 }

Model型号

public class User
{
    public int _UserID { get; set; }
    public string _Email { get; set; }
    public string _UserName { get; set; }
}

Web.Config网页配置

Web.Config File Pasted here in Image Web.Config 文件粘贴在图像中

WebApi.Config WebApi.Config

Namespaces命名空间

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

WebApiConfig Class WebApiConfig 类

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 }
        );
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}

PostMan Request & Response邮递员请求和响应

Headers for Above PostMan Request以上邮递员请求的标题

Access-Control-Allow-Methods →*
Access-Control-Allow-Origin →*
Access-Control-Request-Headers →: *
Access-Control-Request-Method →: *
Allow →POST
Cache-Control →no-cache
Content-Length →72
Content-Type →application/json; charset=utf-8
Date →Wed, 16 Nov 2016 17:50:03 GMT
Expires →-1
Pragma →no-cache
Server →Microsoft-IIS/7.5
X-AspNet-Version →4.0.30319

Thanks for any Helps!!感谢您的帮助!! Got Wasted a Day for this error.为这个错误浪费了一天。

I know this is an old post but, for anyone else looking for a solution to this problem.我知道这是一篇旧帖子,但是对于其他任何正在寻找解决此问题的方法的人来说。 I had this issue and realized that I was posting to my webapi using http but IIS was redirecting my request to https.我遇到了这个问题,并意识到我正在使用 http 发布到我的 webapi,但 IIS 正在将我的请求重定向到 https。 This redirect was causing postman to change the POST to a GET.此重定向导致邮递员将 POST 更改为 GET。 changing my URL to https fixed the problem for me.将我的 URL 更改为 https 解决了我的问题。

here is the solution of your problem这是您问题的解决方案

ASP.NET WebApi : (405) Method Not Allowed ASP.NET WebApi : (405) 方法不被允许

Finally I changed the cookieless="AutoDetect" in web.config to cookieless="UseCookies" and the problem solved.最后,我将 web.config 中的 cookieless="AutoDetect" 更改为 cookieless="UseCookies",问题解决了。

If you have not Enabled CORS decorate your controller as below.如果您尚未启用 CORS,请按如下方式装饰您的控制器。

  [EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")] 

Also put belo code in webapiconfig.cs file还将 belo 代码放在 webapiconfig.cs 文件中

  config.EnableCors();

If you are hosting your endpoints in public api then decorate controller as below.如果您在公共 api 中托管您的端点,则如下装饰控制器。

 [RoutePrefix("api/users")]
    public class usersController : ApiController

Then Get for example,然后获取例如,

   //Get http:192.168.0.0:2210/api/users/
      [Route("~/api/users")]

     //POST  http:192.168.0.0:2210/api/users/
     [Route("~/api/users")] 

    //Get on id
     //POST  http:192.168.0.0:2210/api/users/
     [Route("~/api/users/{id}")] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM