Http error 405 asp net core

I have a very simple API created using ASP.NET Core 2.1. When a client page calls the API from localhost:8080, the API located at localhost:5000 returns HTTP:405. Why? Note that the HTTP GET test ...

I have a very simple API created using ASP.NET Core 2.1. When a client page calls the API from localhost:8080, the API located at localhost:5000 returns HTTP:405.

Why? Note that the HTTP GET test method in AuthController.cs works just as expected. It is only the HTTP POST request returning HTTP:405.

ControllersAuthController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using server.Models;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;

namespace server.Controllers
{
    [Route("api/auth")]
    [ApiController]
    public class AuthController : ControllerBase
    {

        [HttpGet, Route("test")]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpPost, Route("login")]
        public IActionResult Login([FromBody]LoginModel user)
        {
            if (user == null)
            {
                return BadRequest("Invalid client request");
            }

            if (user.UserName == "johndoe" && user.Password == "def@123")
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:5000",
                    audience: "http://localhost:5000",
                    claims: new List<Claim>(),
                    expires: DateTime.Now.AddMinutes(10),
                    signingCredentials: signinCredentials
                );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                return Ok(new { Token = tokenString });
            }
            else
            {
                return Unauthorized();
            }
        }
    }
}

ModelsLoginModel.cs

namespace server.Models
{
    public class LoginModel
    {
        public string UserName { get; set;}
        public string Password { get; set; }
    } 
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace server
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer = "http://localhost:5000",
                    ValidAudience = "http://localhost:5000",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
                };
            });

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:8080");
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors("SiteCorsPolicy");
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

index.html (localhost:8080)

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>JWT Auth</title>
    </head>
    <body>
        <p>Output:</p>
        <div id="output"></div>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script>

            var item =  {
                UserName: "johndoe",
                Password: "def@123" 
            };

            $.ajax({
                type: "POST",
                accepts: "application/json",
                url: '/api/auth/Login',
                contentType: "application/json",
                data: JSON.stringify(item),
                error: function(jqXHR, textStatus, errorThrown) {
                alert("Something went wrong!");
                },
                success: function(result) {
                    console.log('Testing');
                }
            });

        </script>
    </body>
</html>

Содержание

  1. Устранение неполадок приложений веб-API2, работающих в Visual Studio, и сбой на рабочем сервере IIS
  2. Программное обеспечение, используемое в этом руководстве
  3. Причины ошибок HTTP 405
  4. Пример ошибки HTTP 405
  5. Устранение ошибок HTTP 405
  6. Ошибки HTTP 501
  7. Сводка
  8. Troubleshoot Web API2 apps that work in Visual Studio and fail on a production IIS server
  9. Software used in this tutorial
  10. What causes HTTP 405 errors
  11. Example HTTP 405 error
  12. Resolve HTTP 405 errors
  13. HTTP 501 errors
  14. Summary

Устранение неполадок приложений веб-API2, работающих в Visual Studio, и сбой на рабочем сервере IIS

В этом документе объясняется, как устранять неполадки с веб-приложениями API2, развернутыми на рабочем сервере IIS. Он устраняет распространенные ошибки HTTP 405 и 501.

Программное обеспечение, используемое в этом руководстве

Приложения веб-API обычно используют несколько HTTP-команд: GET, POST, PUT, DELETE и иногда PATCH. Это значит, что разработчики могут столкнуться с ситуациями, когда эти команды реализуются другим модулем IIS на рабочем сервере IIS, что приводит к ситуации, когда контроллер веб-API, который работает правильно в Visual Studio или на сервере разработки, вернет ошибку HTTP 405 при развертывании на рабочем сервере IIS.

Причины ошибок HTTP 405

Первым шагом к изучению устранения ошибок HTTP 405 является понимание того, что на самом деле означает ошибка HTTP 405. Основным руководящим документом для HTTP является RFC 2616, который определяет код состояния HTTP 405 как метод not Allowed, и далее описывает этот код состояния как ситуацию, когда «метод, указанный в Request-Line, не разрешен для ресурса, определяемого с помощью URI запроса». Другими словами, HTTP-команда не допускается для конкретного URL-адреса, запрошенного HTTP-клиентом.

В качестве краткого обзора ниже приведены некоторые из наиболее используемых методов HTTP, определенных в RFC 2616, RFC 4918 и RFC 5789:

Метод HTTP Описание
GET Этот метод используется для получения данных из универсального кода ресурса (URI) и, вероятно, наиболее часто используемый метод HTTP.
HEAD Этот метод очень похож на метод GET, за исключением того, что он фактически не извлекает данные из URI запроса. Он просто получает состояние HTTP.
POST Этот метод обычно используется для отправки новых данных в URI; POST часто используется для отправки данных формы.
PUT Этот метод обычно используется для отправки необработанных данных в URI; PUT часто используется для отправки данных JSON или XML в приложения веб-API.
DELETE Этот метод используется для удаления данных из URI.
OPTIONS Этот метод обычно используется для получения списка методов HTTP, поддерживаемых для URI.
COPY MOVE Эти два метода используются с WebDAV, и их назначение является самообязательным.
MKCOL Этот метод используется с WebDAV и используется для создания коллекции (например, каталога) по указанному URI.
PROPFIND PROPPATCH Эти два метода используются с WebDAV, и они используются для запроса или задания свойств для универсального кода ресурса (URI).
БЛОКИРОВКА РАЗБЛОКИРОВКИ Эти два метода используются с WebDAV, и они используются для блокировки или разблокировки ресурса, определяемого универсальным кодом ресурса (URI) запроса при создании.
PATCH Этот метод используется для изменения существующего ресурса HTTP.

Если один из этих методов HTTP настроен для использования на сервере, сервер будет отвечать с состоянием HTTP и другими данными, соответствующими запросу. (Например, метод GET может получить ответ HTTP 200 OK , а метод PUT может получить ответ HTTP 201 Created .)

Если метод HTTP не настроен для использования на сервере, сервер ответит ошибкой HTTP 501 Not Implemented .

Однако если метод HTTP настроен для использования на сервере, но он отключен для заданного URI, сервер будет отвечать с ошибкой HTTP 405 Method Not Allowed .

Пример ошибки HTTP 405

В следующем примере HTTP-запрос и ответ иллюстрируются ситуации, когда HTTP-клиент пытается поместить значение в приложение веб-API на веб-сервере, а сервер возвращает ошибку HTTP, указывающую, что метод PUT не разрешен:

В этом примере HTTP-клиент отправил действительный запрос JSON в URL-адрес приложения веб-API на веб-сервере, но сервер вернул сообщение об ошибке HTTP 405, указывающее, что метод PUT не разрешен для URL-адреса. В отличие от этого, если URI запроса не совпадает с маршрутом для приложения веб-API, сервер вернет ошибку HTTP 404 Not Found .

Устранение ошибок HTTP 405

Существует несколько причин, по которым определенная http-команда может быть запрещена, но существует один основной сценарий, который является главной причиной этой ошибки в IIS: несколько обработчиков определяются для одного и того же глагола или метода, а один из обработчиков блокирует ожидаемый обработчик обработки запроса. В качестве объяснения IIS обрабатывает обработчики от первого до последнего на основе записей обработчика заказов в файлахapplicationHost.config и web.config , где для обработки запроса будет использоваться первая соответствующая комбинация пути, команды, ресурса и т. д.

В следующем примере приведен фрагмент файла applicationHost.config для сервера IIS, возвращающего ошибку HTTP 405 при использовании метода PUT для отправки данных в приложение веб-API. В этом фрагменте определены несколько обработчиков HTTP, и каждый обработчик имеет другой набор методов HTTP, для которых он настроен. Последняя запись в списке является обработчиком статического содержимого, который используется по умолчанию после того, как другие обработчики имели возможность проверить запрос:

В предыдущем примере обработчик WebDAV и обработчик URL-адресов без расширения для ASP.NET (который используется для веб-API) четко определены для отдельных списков методов HTTP. Обратите внимание, что обработчик DLL ISAPI настроен для всех методов HTTP, хотя эта конфигурация не обязательно приведет к ошибке. Однако при устранении ошибок HTTP 405 необходимо учитывать такие параметры конфигурации.

В предыдущем примере обработчик DLL ISAPI не был проблемой; На самом деле проблема не была определена в файлеapplicationHost.config для сервера IIS. Проблема была вызвана записью, которая была сделана в файлеweb.config при создании приложения веб-API в Visual Studio. В следующем фрагменте файла web.config приложения отображается расположение проблемы:

В этом фрагменте обработчик URL-адресов без расширения для ASP.NET переопределен для включения дополнительных методов HTTP, которые будут использоваться с приложением веб-API. Однако, так как для обработчика WebDAV определен аналогичный набор методов HTTP, возникает конфликт. В этом конкретном случае обработчик WebDAV определяется и загружается службами IIS, даже если WebDAV отключен для веб-сайта, включающего приложение веб-API. Во время обработки HTTP-запроса PUT IIS вызывает модуль WebDAV, так как он определен для команды PUT. При вызове модуля WebDAV он проверяет конфигурацию и видит, что он отключен, поэтому возвращает ошибку http 405 Method Not Allowed для любого запроса, напоминающего запрос WebDAV. Чтобы устранить эту проблему, необходимо удалить WebDAV из списка модулей HTTP для веб-сайта, на котором определено приложение веб-API. В следующем примере показано, как это может выглядеть:

Этот сценарий часто встречается после публикации приложения из среды разработки в рабочую среду IIS, и это происходит потому, что список обработчиков и модулей отличается от среды разработки и рабочей среды. Например, если вы используете Visual Studio 2012 или более поздней версии для разработки приложения веб-API, IIS Express является веб-сервером по умолчанию для тестирования. Этот веб-сервер разработки — это уменьшенная версия полной функциональности IIS, которая поставляется в серверном продукте, и этот веб-сервер разработки содержит несколько изменений, добавленных для сценариев разработки. Например, модуль WebDAV часто устанавливается на рабочем веб-сервере под управлением полной версии IIS, хотя он может не использоваться. Версия разработки СЛУЖБ IIS (IIS Express) устанавливает модуль WebDAV, но записи для модуля WebDAV намеренно закомментированы, поэтому модуль WebDAV никогда не загружается на IIS Express, если только вы не измените параметры конфигурации IIS Express, чтобы добавить функциональные возможности WebDAV в установку IIS Express. В результате веб-приложение может работать правильно на компьютере разработки, но при публикации приложения веб-API на рабочем веб-сервере IIS могут возникнуть ошибки HTTP 405.

Ошибки HTTP 501

  • Указывает, что на сервере не реализованы определенные функциональные возможности.
  • Как правило, обработчик не определен в параметрах IIS, которые соответствуют HTTP-запросу:
    • Вероятно, указывает на то, что что-то не было установлено правильно в IIS или
    • Что-то изменило параметры IIS, чтобы обработчики не были определены, поддерживающие конкретный метод HTTP.

Чтобы устранить эту проблему, необходимо переустановить любое приложение, которое пытается использовать метод HTTP, для которого он не имеет соответствующих определений модуля или обработчика.

Сводка

Ошибки HTTP 405 возникают, когда метод HTTP не разрешен веб-сервером для запрошенного URL-адреса. Это условие часто возникает, когда определенный обработчик был определен для определенной команды, и этот обработчик переопределяет обработчик, который вы ожидаете обработать запрос.

Источник

Troubleshoot Web API2 apps that work in Visual Studio and fail on a production IIS server

This doc explains how to troubleshoot Web API2 apps that are deployed to a production IIS server. It addresses common HTTP 405 and 501 errors.

Software used in this tutorial

Web API apps typically use several HTTP verbs: GET, POST, PUT, DELETE, and sometimes PATCH. That being said, developers may run into situations where those verbs are implemented by another IIS module on their production IIS server, which leads to a situation where a Web API controller that works correctly in Visual Studio or on a development server will return an HTTP 405 error when it is deployed to a production IIS server.

What causes HTTP 405 errors

The first step toward learning how to troubleshoot HTTP 405 errors is to understand what an HTTP 405 error actually means. The primary governing document for HTTP is RFC 2616, which defines the HTTP 405 status code as Method Not Allowed, and further describes this status code as a situation where «the method specified in the Request-Line is not allowed for the resource identified by the Request-URI.» In other words, the HTTP verb is not allowed for the specific URL that an HTTP client has requested.

As a brief review, here are several of the most-used HTTP methods as defined in RFC 2616, RFC 4918, and RFC 5789:

HTTP Method Description
GET This method is used to retrieve data from a URI, and it probably the most-used HTTP method.
HEAD This method is much like the GET method, except that it doesn’t actually retrieve the data from the request URI — it simply retrieves the HTTP status.
POST This method is typically used to send new data to the URI; POST is often used to submit form data.
PUT This method is typically used to send raw data to the URI; PUT is often used to submit JSON or XML data to Web API applications.
DELETE This method is used to remove data from a URI.
OPTIONS This method is typically used to retrieve the list of HTTP methods that are supported for a URI.
COPY MOVE These two methods are used with WebDAV, and their purpose is self-explanatory.
MKCOL This method is used with WebDAV, and it is used to create a collection (e.g. a directory) at the specified URI.
PROPFIND PROPPATCH These two methods are used with WebDAV, and they are used to query or set properties for a URI.
LOCK UNLOCK These two methods are used with WebDAV, and they are used to lock/unlock the resource identified by the request URI when authoring.
PATCH This method is used to modify an existing HTTP resource.

When one of these HTTP methods is configured for use on the server, the server will respond with the HTTP status and other data that is appropriate for the request. (For example, a GET method might receive an HTTP 200 OK response, and a PUT method might receive an HTTP 201 Created response.)

If the HTTP method is not configured for use on the server, the server will respond with an HTTP 501 Not Implemented error.

However, when an HTTP method is configured for use on the server, but it has been disabled for a given URI, the server will respond with an HTTP 405 Method Not Allowed error.

Example HTTP 405 error

The following example HTTP request and response illustrate a situation where an HTTP client is attempting to PUT value to a Web API app on a web server, and the server returns an HTTP error which states that the PUT method is not allowed:

In this example, the HTTP client sent a valid JSON request to the URL for a Web API application on a web server, but the server returned an HTTP 405 error message which indicates that the PUT method was not allowed for the URL. In contrast, if the request URI did not match a route for the Web API application, the server would return an HTTP 404 Not Found error.

Resolve HTTP 405 errors

There are several reasons why a specific HTTP verb may not be allowed, but there is one primary scenario that is the leading cause of this error in IIS: multiple handlers are defined for the same verb/method, and one of the handlers is blocking the expected handler from processing the request. By way of explanation, IIS processes handlers from first to last based on the order handler entries in the applicationHost.config and web.config files, where the first matching combination of path, verb, resource, etc., will be used to handle the request.

The following example is an excerpt from an applicationHost.config file for an IIS server that was returning an HTTP 405 error when using the PUT method to submit data to a Web API application. In this excerpt, several HTTP handlers are defined, and each handler has a different set of HTTP methods for which it is configured — the last entry in the list is the static content handler, which is the default handler that is used after the other handlers have had a chance to examine the request:

In the preceding example, the WebDAV handler and the Extension-less URL Handler for ASP.NET (which is used for Web API) are clearly defined for separate lists of HTTP methods. Note that the ISAPI DLL handler is configured for all HTTP methods, although this configuration will not necessarily cause an error. However, configuration settings like this need to be considered when troubleshooting HTTP 405 errors.

In the preceding example, the ISAPI DLL handler was not the problem; in fact, the problem was not defined in the applicationHost.config file for the IIS server — the problem was caused by an entry that was made in the web.config file when the Web API application was created in Visual Studio. The following excerpt from the application’s web.config file shows the location of the problem:

In this excerpt, the Extension-less URL Handler for ASP.NET is redefined to include additional HTTP methods that will be used with the Web API application. However, since a similar set of HTTP methods is defined for the WebDAV handler, a conflict occurs. In this specific case, the WebDAV handler is defined and loaded by IIS, even though WebDAV is disabled for the website that includes the Web API application. During the processing of an HTTP PUT request, IIS calls the WebDAV module since it is defined for the PUT verb. When the WebDAV module is called, it checks its configuration and sees that it is disabled, so it will return an HTTP 405 Method Not Allowed error for any request that resembles a WebDAV request. To resolve this issue, you should remove WebDAV from the list of HTTP modules for the website where your Web API application is defined. The following example shows what that might look like:

This scenario is often encountered after an application is published from a development environment to an IIS production environment, and this occurs because the list of handlers/modules is different between your development and production environments. For example, if you are using Visual Studio 2012 or later to develop a Web API application, IIS Express is the default web server for testing. This development web server is a scaled-down version of the full IIS functionality that ships in a server product, and this development web server contains a few changes that were added for development scenarios. For example, the WebDAV module is often installed on a production web server that is running the full version of IIS, although it may not be in use. The development version of IIS, (IIS Express), installs the WebDAV module, but the entries for the WebDAV module are intentionally commented out, so the WebDAV module is never loaded on IIS Express unless you specifically alter your IIS Express configuration settings to add WebDAV functionality to your IIS Express installation. As a result, your web application may work correctly on your development computer, but you may encounter HTTP 405 errors when you publish your Web API application to your production IIS web server.

HTTP 501 errors

  • Indicates the specific functionality has not been implemented on the server.
  • Typically means that there is no handler defined in your IIS settings which matches the HTTP request:
    • Probably indicates that something was not installed correctly on IIS or
    • Something has modified your IIS settings so that there are no handlers defined that support the specific HTTP method.

To resolve that issue, you would need to reinstall any application that is attempting to use an HTTP method for which it has no corresponding module or handler definitions.

Summary

HTTP 405 errors are caused when an HTTP method is not allowed by a web server for a requested URL. This condition is often seen when a particular handler has been defined for a specific verb, and that handler is overriding the handler that you expect to process the request.

Источник

When Deployed to Live Environment

Ran into this issue after deploying our latest web app built on ASP.NET 5 (now known as Core 1.0), MVC 6 with Web API.

We are using HostForLife shared servers to host the site, a solid yet inexpensive choice for any of you looking for hosting recommendations.

We found that both GET and POST methods worked fine but neither PUT or DELETE worked at all. We were getting a 405 Method Not Allowed error.

From reading up on this it seems to be to do with something called WebDav disallowing these action names by default. You will need to override this setting in order to get it to work.

To do this open up your web.config file. There are 2 web.config files in your project – The one you want to open is the one INSIDE the wwwroot folder.

Inside the web.config add the following 3 lines inside the already existing system.webServer node:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

Now just save your file and publish changes to your live site.

Update: Changes in ASP.NET Core 2.0 and Visual Studio 2017

It has recently come to my attention that in some of the newer project templates in Visual Studio 2017 (sidenote: if you haven’t moved from 2015 to 2017 yet then you should, it can be downloaded here) there is in fact no web.config file inside the wwwroot folder. One of the commenters below has mentioned that they just put the above code into the web.config file that was still there outside of the wwwroot folder at the project root level and that it worked fine there also.

I have also seen some newer project templates (as of April 2018) that did not include any web.config file at all. From what I have read there is a push to replace web.config files with appsettings.json files. In this instance I’m not actually sure what best practice is, as I have yet to deploy one of these newer ASP.NET Core websites. If anyone has any ideas let me know. My gut tells me that adding a web.config file yourself and adding in the code there should work fine, but as I said, there may be a newer, better way to do it in 2.0.

Cover image for Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Sandeep Kumar

Reason:

The WebDAVModule set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors.

Solution:

To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under the system.webServer.

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

Enter fullscreen mode

Exit fullscreen mode

There may be 2 web.config files in your project, if that is the case then update the one that is inside the wwwroot folder.

Also with the latest version of .Net CORE (2.0 and above), there might be a case of no web.config file available at all, if that is your case then add a web.config file on your own.

Note:

If you are facing the same issue with multiple APIs hosted on the same server, then either you can add the above entries under web.config file of all the affected API’s or you can remove the below entry of WebDAVModule from ApplicationHost.config file under the module section:

<add name="WebDAVModule" />

Enter fullscreen mode

Exit fullscreen mode

ApplicationHost.config can be found at

C:WindowsSystem32inetsrvconfig

Hope that helps !!!


Originally published at http://diary-techies.blogspot.com on
January 07, 2019.

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Http error 404 yandex
  • Http error 404 wordpress
  • Http error 404 the requested resource is not found что это значит
  • Http error 404 the requested resource is not found как исправить
  • Http error 404 the requested resource is not found xampp

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии