gpt4 book ai didi

c# - 尝试创建多个唯一的短 URL

转载 作者:行者123 更新时间:2023-12-04 10:34:19 24 4
gpt4 key购买 nike

我想创建一个 post 方法,当给定一个包含多个 JSON 网址的正文时,该方法返回一个缩短的网址列表。

这是我的post方法:

public class MyServices : Service
{
public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
{
using (Task4URLEntities db = new Task4URLEntities())
{
var urls = new List<string>();
foreach (string LongUrl in request.LongUrl)
{
var item = new ShortURLs
{
LongUrl = LongUrl,
ShortUrl = GetUrl(),
DateCreated = DateTime.Now
};
urls.Add($"http://localhost/{item.ShortUrl}");
db.ShortURLs.Add(item);
}

var campaign = new Campaign
{
CampaignName = request.CampaignName,
Enddate = request.Enddate,
Startdate = request.Startdate
};

db.Campaign.Add(campaign);

try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}

return new CreateShortUrlResponse
{
Response = urls,
CampaignId = campaign.CampaignId
};
}
}

public string GetUrl()
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[5];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
return finalString;
}

}

我的问题是,当我在 Postman 上发送我的帖子请求以获取 JSON 格式的 URL 列表时,如果我再次单击发送,我将获得唯一的 URL 作为第一篇帖子的响应,然后我将得到一个响应,其中每个返回的短 URL 是相同的。

我该如何纠正?

最佳答案

我猜当您说“每个返回的短 URL 都相同”时,您的意思是 CreateShortUrlResponse.Response 属性包含完全相同的 URL n 次数,其中 n 是您请求的 URL 数量。基于这种行为,我还假设这是一个 .NET Framework 项目,而不是一个 .NET Core 项目。
如果是这种情况,那么问题在于在如此紧密的循环中创建 Random 的新实例会导致每个实例都使用完全相同的种子值创建。当您在 .NET Framework 中使用空构造函数创建 Random 的实例时,它使用 Environment.TickCount 作为种子。因此,如果您快速连续创建两个 Random 实例,它们将具有相同的种子并因此生成相同的值。
documentation on Random speaks to this

On the .NET Framework, initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process.

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

However, the Random class isn't thread safe. If you call Random methods from multiple threads, follow the guidelines discussed in the next section.


因此,您可以使 Random 实例成为 MyServices 类的成员,而不是每次调用 GetUrl 时都创建一个新实例。
public class MyServices : Service
{
public object Post(CreateShortUrlRequest request) //Post an array/list of URLs to the database and get a respective list of short URL
{
using (Task4URLEntities db = new Task4URLEntities())
{
var urls = new List<string>();
foreach (string LongUrl in request.LongUrl)
{
var item = new ShortURLs
{
LongUrl = LongUrl,
ShortUrl = GetUrl(),
DateCreated = DateTime.Now
};
urls.Add($"http://localhost/{item.ShortUrl}");
db.ShortURLs.Add(item);
}

var campaign = new Campaign
{
CampaignName = request.CampaignName,
Enddate = request.Enddate,
Startdate = request.Startdate
};

db.Campaign.Add(campaign);

try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.WriteAsync("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}

return new CreateShortUrlResponse
{
Response = urls,
CampaignId = campaign.CampaignId
};
}
}

public string GetUrl()
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[5];
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[_rng.Next(chars.Length)];
}
var finalString = new String(stringChars);
return finalString;
}
private Random _rng = new Random();
}

关于c# - 尝试创建多个唯一的短 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60262932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com