[C#] There will be some problems if the URL is not UrlEncoded.

Welcome to "Little 5 Lecture Hall", hello everyone, I am Full Stack Little 5.
This is the third article in 2024. This article is a practical sequence of C# knowledge points. The blogger has limited abilities and understanding. If there is anything wrong, please correct me!

Insert image description here

Preface

In the last article, we have learned that if address encoding is not performed, there will be data loss or incorrect data.
As for URL errors, security issues, and compatibility issues, we will not explore them for the time being. We will only explore them through non-encoding parsing.

data lost

This is easier to understand. It means that the value of the address parameter passed is incomplete, only part of it, and the other part of the data is lost.
The following will demonstrate the effect of A place initiating a get request for an http address, passing unencoded address parameters, and receiving parameter values ​​on the target interface.

Effect

Assume that the address parameters are: name=Zhang San&Xiao Ming&age=20&21
The complete request address is: https://localhost:7250/WeatherForecast?name=Zhang San&Xiao Ming&age=20&21

Insert image description here
Insert image description here
The & symbol in the address parameter is used to separate different parameter variables, and the = equal symbol is followed by the parameter value.

From the picture above, you can see that the value of the name parameter should be Zhang San&Xiao Ming, and the value of the age parameter should be 20&21. In fact, the obtained values ​​are name=Zhang San, age=20.
The reason is that the value of the address parameter is from the = equal sign to the end of the next & sign. Without the & sign, it means all the values ​​after the = equal sign.

Therefore, if the URL address parameter is not encoded when calling the interface through http request, data is likely to be lost.

Requester code

private async Task HttpGet()
{
    
    
    string urlValue = $"https://localhost:7250/WeatherForecast?name=张三&小明&age=20&21";

    using (HttpClient client = new HttpClient())
    {
    
    
        try
        {
    
    
            HttpResponseMessage response =await client.GetAsync(urlValue);
            response.EnsureSuccessStatusCode(); // 确保请求成功,否则会抛出异常
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException ex)
        {
    
    
            Console.WriteLine($"请求失败:{
      
      ex.Message}");
        }
    }
}

Interface code

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get(string name, int age)
{
    
    
    string urlParam = Request.QueryString.Value;

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
    
    
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

Data encoding

Data encoding using HttpUtility.UrlEncode

Effect

As you can see from the picture below, the .net core mvc framework itself will automatically decode the encoded data.
Insert image description here
Insert image description here

Requester code

After encoding the data, I found that the interface cannot be called. That is because the age parameter of the interface receives integer data. Because the framework has its own rules, it needs to be changed to a string type.

https://localhost:7250/WeatherForecast?name=%e5%bc%a0%e4%b8%89%26%e5%b0%8f%e6%98%8e&age=20%2621

private async Task HttpGet()
{
    
    
    string urlValue = $"https://localhost:7250/WeatherForecast?name={
      
      HttpUtility.UrlEncode("张三&小明")}&{
      
      HttpUtility.UrlEncode("age=20&21")}";

    using (HttpClient client = new HttpClient())
    {
    
    
        try
        {
    
    
            HttpResponseMessage response =await client.GetAsync(urlValue);
            response.EnsureSuccessStatusCode(); // 确保请求成功,否则会抛出异常
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException ex)
        {
    
    
            Console.WriteLine($"请求失败:{
      
      ex.Message}");
        }
    }
}

Interface code

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get(string name, string age)
{
    
    
    string urlParam = Request.QueryString.Value;

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
    
    
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

Prevent attacks

The address parameter is initiated by the attacker, and he can pass it without encoding. How to prevent this attack, you can take the following measures.

1. Perform input checking and filtering.
Check and filter the passed address parameters on the server side to ensure that they comply with the expected format, type, range and rules. For example, you can check whether the parameters are legal URLs or impose certain input data format restrictions.

2. Encode the address parameters.
URL-encode the address parameters or other suitable encoding to ensure that the data passed is safe and cannot be exploited by attackers.

3. Use HTTPS protocol for data transmission.
Using HTTPS protocol to encrypt data transmission can ensure the security of the connection through encryption at the transport layer or network layer. It can effectively prevent data from being stolen by man-in-the-middle attacks and improve protection capabilities.

4. Avoid passing sensitive data in the URL.
Avoid passing sensitive data in the address parameters. It is best to use the POST method when transmitting more sensitive data, and do not use the GET method.

Summary: Review the past and learn the new. Reviewing knowledge points at different stages will lead to different understandings and understandings. The blogger will consolidate the knowledge points and share them with everyone in a practical way. If it can be helpful and gainful, this will be a blog post. The Lord’s greatest creative motivation and honor. I also look forward to meeting more outstanding new and old bloggers.

Guess you like

Origin blog.csdn.net/lmy_520/article/details/135419702