Search code examples
c#web.net-coreweb-configcsproj

How to add rules to .net core project in *.csproj


I want to add rules to a .net core project. In a .net normal project I have the facility to edit directly the web.config file

Actually I need to achieve this, in a .net core project

<?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=".\RazorWeb.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="OutOfProcess" />
    </system.webServer>
  </location>
  <system.webServer>
    <rewrite>
     <!---START:ADD THIS RULES-->
      <rules>
        <rule name="httpTohttps" stopProcessing="true">
          <match url="^(.*)$" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
        </rule>
      </rules>
      <!---END:ADD THIS RULES-->
    </rewrite>
  </system.webServer>
</configuration>

Well since I Introduced in .net core I noticed the template projects doesn't came with this .config file, however the templates use the .csproj file and .json files to add configurations etc...

The main idea is how can achieve this in a .net core project, I was seaching in diferents sites, the docs of microsoft are not totally clear for my in this aspect, the nearest thing that I found was this

https://roslyn-analyzers.readthedocs.io/en/latest/config-analyzer.html But doesn't work for me


Solution

  • See this. You should use the middleware instead of web.config to enforce https. https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&tabs=visual-studio

    You can still include a web.config file in your .NET Core project when needed. In fact, one is generated when you hit Publish and don't already have one, which can give you a starting point to make a custom one.

    Do one of the following:

    1. Add the "Web Configuration" template in Add Item like this answer which nicely contains a screenshot: https://stackoverflow.com/a/53731666/691749
    2. Create your own web.config instead, and set it to always copy to output directory. This will replace the auto-generated one on Publish.

    There's been a lot of confusing information about this file in particular. Here's a decent question with decent answers. Am confused about web.config in .NET Core