Domas Jonaitis
Domas Jonaitis

Reputation: 11

POST 405 (Method Not Allowed) error on Azure using Blazor, but everything works on localhost

I just finished my little project with .NET 6, Blazor on Visual Studio 2022, and everything works just fine on localhost, but when I published it on Azure, and I try to register again on my app, I'm receiving this error in the console:

POST https://domasjonaitis.azurewebsites.net/api/auth/register 405 (Method Not Allowed)

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: ExpectedStartOfValueNotFound, T Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: ExpectedStartOfValueNotFound, T Path: $ | LineNumber: 0 | BytePositionInLine: 0.
 ---> System.Text.Json.JsonReaderException: ExpectedStartOfValueNotFound, T LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& , ExceptionResource , Byte , ReadOnlySpan`1 )
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte )
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte )
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.Serialization.JsonConverter`1[[BlazorApp.Shared.ServiceResponse`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], BlazorApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
   Exception_EndOfInnerExceptionStack
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& , JsonReaderException )
   at System.Text.Json.Serialization.JsonConverter`1[[BlazorApp.Shared.ServiceResponse`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], BlazorApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
   at System.Text.Json.JsonSerializer.ReadCore[ServiceResponse`1](JsonConverter , Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
   at System.Text.Json.JsonSerializer.ReadCore[ServiceResponse`1](JsonReaderState& , Boolean , ReadOnlySpan`1 , JsonSerializerOptions , ReadStack& , JsonConverter )
   at System.Text.Json.JsonSerializer.ContinueDeserialize[ServiceResponse`1](ReadBufferState& , JsonReaderState& , ReadStack& , JsonConverter , JsonSerializerOptions )
   at System.Text.Json.JsonSerializer.<ReadAllAsync>d__65`1[[BlazorApp.Shared.ServiceResponse`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], BlazorApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__4`1[[BlazorApp.Shared.ServiceResponse`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], BlazorApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at BlazorApp.Client.Services.AuthService.AuthService.Register(UserRegister request)
   at BlazorApp.Client.Pages.Register.HandleRegistration()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )

And the same happens if I try to login with an existing (which is [email protected] 123123).

I followed through many similar threads that I found, but none of them worked.

You can find my project with all the files included on my GitHub page: https://github.com/domasjohn/BlazorApp

And here is my azure website, that you can check out by yourself: https://domasjonaitis.azurewebsites.net/

Also, I'm a total new beginner, so a simple explanation with the detailed instructions would be appreciated 🙏

Thanks.

Upvotes: 1

Views: 1686

Answers (3)

James McCormack
James McCormack

Reputation: 9944

Just wanted to say that today I have had a problem where a Blazor WASM site with API back end that works locally was returning 405 Method Not Allowed for just one POST endpoint, when on our UAT Azure environment.

After a lot of headscratching I checked the Azure Application Insights logs and found the endpoint was actually throwing an unhandled exception due to an environmental problem. When I fixed the environmental problem it started working OK.

Then I realised that on UAT, we set up exception handling to route to an ExceptionHandler - which hadn't been set up. The 405 was being returned from that :D

So basically, the 405 might be a red herring, and indicator of some other underlying exception.

Upvotes: 1

Edgar Gomez
Edgar Gomez

Reputation: 164

Add this to the web.config

<modules runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule" />
</modules>

It should look like this

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\BlazorAppInventory.Server.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
      <modules runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule" />
      </modules>
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 6fdbcfbf-a2a4-4aab-971c-55d8872341a5-->

Upvotes: 0

Thiago Custodio
Thiago Custodio

Reputation: 18387

I could not check your website as it's stopped, but I do believe it's a CORS issue. All you have to do is add the following to your Startup.cs class:

services.AddCors(opt =>
        {
            opt.AddPolicy(name: _policyName, builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

here's a full sample of how it will look like:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    private readonly string _policyName = "CorsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(opt =>
        {
            opt.AddPolicy(name: _policyName, builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });
        services.AddControllers();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseCors(_policyName);
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Upvotes: 1

Related Questions