Blazor

Blazor Topics. A ASP .Net Core Framework.

  • .Net,  Microsoft

    Dotnet 6 API with a HttpDelete and that 405 Method not allowed error

    As we can tell from the title of the Post, we are going to talk about figuring out why in a client app one gets a Http Status code of 405 (Method Not Allowed).

    When does this happen? Usually when a http request does a  http PUT or DELETE. Yet, when one uses Swagger (openAPI) or Postman to directly call the same API Delete or Put, it works!  This is starting to feel like a CORS issue, right? Read On ==>

    So 405! Indeed looking at the surface of what is going on, one thinks Ah! CORS is at it again! Absolutely, this is what it feels like. After all, a Swagger/Postman GET/DELETE call under the same http domain works. But the moment one moves to a Client App coming in from a different domain (i.e. a different port on localhost, because different ports are also considered a different domain in terms of CORS), the Http PUT/DELETE stops working and throws a 405.

    We are using VS2022 with Dotnet 6.0.100-rc.2.21505.57 (so the latest VS2022 and Dotnet RC 6 as of the writing of this post)

    Wow… let’s step into how to rein in CORS…. We start in the API project in the Startup class.

    In Configure Services =>

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithMethods("GET","PUT","DELETE","POST","PATCH") //not really necessary when AllowAnyMethods is used.
            );
    });
    

    We build a CORS policy  (yes one can remove the .WithMethods clause)

    And of course we add in the Configure method =>

    app.UseRouting();
    app.UseCors("CorsPolicy");

    And everything is right with the world… Let’s do a Delete in a client app. Meaning we are doing HttpClient Delete to a rest url that contains the id:

    Yeap a hard 405… What the what What?
    After digging through lots of readings on the topic of CORS 405 PUT/DELETE, DotNet 6 issues (with not much luck), I stepped upon the answer with a bit of thinking about the problem….

    In my Controller we have this as the delete method header =>

    [HttpDelete("id")]
    public async Task<IActionResult> Delete(int id)
    { ...

    Seems simple enough, it works in the Swagger interface for testing the API. I validated that the client is using and passing the correct url and id. WHAT!?

    Look closely at the [HttpDelete… tag. Notice anything? If one said, “Duh, ScottGeek- you need to wrap the “id” within {}” then YEAP!
    That would be the issue. The real question is why does this seem work in the Swagger UI for the api but not in a app using HttpClient?

    I have absolutely no idea why (yes I could get Fiddler out and start digging deep, nope) In this case what seems like a CORS acting up issue (405 on a cross domain request), yeah it’s not, or is it? This seems to be a bug somewhere, I suspect, in the OpenAPI (swagger) bits. Why in the OpenAPI? because it should reflect the same 405 when the API Method tag is not 100% correct.

    But let’s not just pick on OpenAPI. The fact that DotNet 6 allows both [HttpDelete(“id”)] and [HttpDelete(“{id}”)] without issuing some kind of build blowup or at least a green squiggle on the one that is in error… well I give it to ya… feels like a bug.

    Put the {} around the id and….

    Also, don’t forget to check one’s HttpPut as well…

    ~SG

  • Blazor,  Microsoft

    Blazor with dotnet watch run in the Pre-Dotnet 6 and VS 2022 days

    Oh, how we do wait for the release of dotnet 6 and most important VS 2022. Why? Well the promise of hot-reload without hoops to jump through.

    For the most part in VS 2019 16.10.4, “hot-reload” of a Blazor app is not too bad <= Circle that “not too bad”- it does actually work… mostly! Yes, I do refer to the “dotnet watch run”. It does detect changes in your Blazor files and reload the browser page… yeah, BUT it does have issues. Here comes the list….

    It doesn’t detect new files added… go ahead add a new razor page while your project is in “dotnet watch run” – nope it will not find it no matter how many times you hard refresh the browser. Not only razor pages, but new stylesheets- yeap, it’s not going to find those either!

    It has issues when you make too many complicated changes in your code. Yes compile errors that don’t go away.

    It interferes with an already “flaky” intellicode/intellisense… My goodness talking about annoying! Already half the time, bootstrap intellisense stops working on razor pages. And what the hell happened to code snippets? (Probably less about hot-reload than this version of VS being riddled with bugs!)

    Ok, I’m mostly over that now…. deep breath… 1…2…3…4… Alright.

    Let’s get to the point, the matter of always having to type in that “dotnet watch run”, stop it, and type it in again… what’s the point? Let’s create a launch profile so that we can tack this into VS (gee you think the Blazor Template should already have that? Yeap it should). Here we go:

     

    "Watch": {
          "commandName": "Executable",
          "launchBrowser": true,
          "launchUrl": "http://localhost:5000/",
          "commandLineArgs": "watch run",
          "workingDirectory": "$(ProjectDir)",
          "executablePath": "dotnet.exe",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }

    In your launchSettings.Json file, place the code above in the “Profile” section…. Match sure this is in the “PROFILE” section!

    Now let the magic begin… well mostly… When you tap the “Watch” on the Build/Debug drop down… that lovely “dotnet watch run” will execute in a window… and now you to can experience the “buggy” hot-reload of a Blazor app. 😎
    ~SG

  • Blazor,  Microsoft

    Blazor: And the Identity Scaffolding Mess

    Ok, back around to the annoying bin. Let’s talk adding Identity to a Blazor Web Assembly app…

    Out of the box when you start with a Blazor WebAss project using Identity and of course ASP Core hosted (I’m using preview 2). You then decide that all of the hidden razor pages really need to be customized (don’t even get me started on Hidden razor pages). Well there is a way to do just that.

    You Add Scaffolded Item to the Server project and select Identity (nope not going to show you that- there’s plenty of how-to on the internet). I wait while you go figure out how-to do that……   Wait  wait wait wait….

    All right, now you have those missing identity pages  up in Areas/Identity/Pages/Account – and you have an app that compiles and run, right? Well…. NO you don’t. Because now your app is broken… And that’s where we start… Let’s fix it.

    The Fix –

      RegisterConfirmation.chtml.cs  (if during your scaffold you selected the RegisterConfirmation page to include in the Areas/Identity/Pages/Account)
        You will need to add the reference using Microsoft.AspNetCore.Identity; – this is missing from the code behind.

      The Scaffold also creates an another wwwroot folder in the .Server project – The app runs into conflicts with css etc… 
        All you need to do here is delete the wwwroot folder from the .Server project. The Blazor will come up normal.

    Now, there maybe other compile errors depending on the mix of .dot core you have, etc. You will just need to work through those.

    Another annoying thing that happens when you mix Blazor and these older razor identity pages… is how the identity system works when you logout. Normally one likes to have the app navigate back to the home page when one logs out. This is doable but not in the box on the template.

    This is easy fix….

    In your client project in the Pages folder, you have a Authentication.razor file:

    @page "/authentication/{action}"
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    <RemoteAuthenticatorView Action="@Action" />
    
    @code{
        [Parameter] public string Action { get; set; }
    }

    This is the default page… Let’s make a change…

    @page "/authentication/{action}"
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @inject NavigationManager navMGR
    <RemoteAuthenticatorView Action="@Action">
        <LogOutSucceeded>
          @{navMGR.NavigateTo("/");}
        </LogOutSucceeded>
    </RemoteAuthenticatorView>
    
    @code{
        [Parameter] public string Action { get; set; }
    }

    We injected the NavigationManager, because we want to navigate to the home page. 
     One see that in the RemoteAuthenticationView we have some options… LogOutSucceeded is a component option that allows us to do something, when the user has logged out with no errors. 
     This is good place to put a NavigateTo Blazor command… and as we see we can force the app (from the box) to go to the home page.

    Neat… 

    Now yes, the errors and problems are annoying… they have been for the scaffold for awhile now… but hopefully as Blazor moves out of preview, these things will be fixed.

    ~ScottGeek   Happy Blazoring….

     

     

     

     

     

  • Blazor,  Microsoft

    Blazor and EF Core to Nowhere land.

    In the long decent into “Experimental” frameworks- this one being Blazor, I’ve been finding some challenges with getting Blazor to work with the latest EF Core. There’s a few examples of Blazor being used with EF Core (i.e. the CRUD example that’s floating around the inter-Tubes), but nothing that seems to work with the latest Blazor Lang template in the latest VS release.

    One can go to a lower EF Core version, well mostly… I’ve yet to get my Blazor Hosted Core test app to compile…. let alone the DB-Context to Scaffold… it just spews errors no matter which direction I go in… Oh Bother….

    I have to remember that Blazor is “Experimental” – But it would be nice if would keep up with the forward moving components like EF Core and the latest VS releases. I wonder what all of the Blazor Template releases are doing- seems like each time I run up VS there’s a new Blazor Lang Update. Curious…