Prevent url decoding of values in csproj files

37 Views Asked by At

I have the following scenario. I call a tool to generate code from data obtained via a rest service, like so:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <Target Name="Generate code" ...>
        <Exec Command="dotnet tool run WebApiTool QueryUrl=https%3A%2F%2Fmy-web-api.azurewebsites.net%2Fapi%2Fv2%2Fexport%3Ftype%3Djson%26excludes%3DexcludeThis%2CexcludeThat" />
  </Target>
</Project>

The URL is encoded, decoded it would look like this https://my-web-api.azurewebsites.net/api/v2/export?type=json&excludes=excludeThis,excludeThat

It is important, that the tool gets the ENCODED value, because WebApiTool is a legacy tool and it basically looks for the '=' character to parse commandline options.

My problem is that whenever I execute 'dotnet build', the encoded URL string gets automatically decoded before being passed to the WebApiTool.

Is there any way to prevent this?

1

There are 1 best solutions below

0
Christian.K On

You might want to also check out this.

You have several options to work around this issue:

  • Read the encoded URL from an external/separate file. So that it never appears in the project file as a literal string.

  • "Mask" the literal string in the project file.


<Project>
  <Target Name="Example1">
    <!-- Here "url.txt" just constains a single line of text, the encoded url. -->
    <ReadLinesFromFile File="url.txt">
      <Output TaskParameter="Lines" ItemName="Urls"/>
    </ReadLinesFromFile>
    <!-- We know there is only one line in the file, so simply use item group as property value -->
    <PropertyGroup>
      <Url>@(Urls)</Url>
    </PropertyGroup>
    <!-- Additional escaping of '%' to '%%' is required, because the "Command" will be run as a (temporary) batch file.
    That in turn, will interpret %n as command line argument #n, which is not set and thus would remove all %n from the
    resulting output. -->
    <Exec Command="echo $(Url.Replace('%', '%%'))" />
  </Target>

  <Target Name="Example2">
    <PropertyGroup>
      <!-- Mask percent in the URL string so that it is not recognized -->
      <Url>https[%]3A[%]2F[%]2Fmy-web-api.azurewebsites.net[%]2Fapi[%]2Fv2[%]2Fexport[%]3Ftype[%]3Djson[%]26excludes[%]3DexcludeThis[%]2CexcludeThat</Url>
    </PropertyGroup>
    <Exec Command="echo $(Url.Replace('[%]', '%%'))" />
  </Target>
</Project>