如何重定向到来自中数据库的url.NET



我有一个内置的web api。NET,在一个端点中,我想重定向到一个和插入数据库的代码匹配的url。端点将代码作为入口,我应该重定向到相应的url。为此,我使用了Redirect方法,该方法实际上不起作用。我做了Console。如果url为null或为空,但它存在,则写入以打印。这是我的控制器的代码:

[HttpGet("{hash}")]
// [ProducesResponseType(302)]
//[ProducesResponseType(404)]
public async Task<IActionResult> redirectUrl(string hash)
{
var t = await new ServiceUrl(_ctx).GetTarget2(hash);
int a = 0;
foreach (Model.Data.DAO.Url i in t)
{

if (i != null)
{
a=a+1;
}
}
if (a==0)
{
return new TimeoutExceptionObjectResult(error: "Not Found",503);
}else
if (DateTime.Compare(DateTime.Now, t.ElementAt(0).ExpireAt) > 0)
{
t.ElementAt(0).state = "expire";
_ctx.Entry(t.ElementAt(0)).State = EntityState.Modified;
await _ctx.SaveChangesAsync();
return new TimeoutExceptionObjectResult(error: "Url expiré",501);
}
string url= t.ElementAt(0).UrlOrigin;
Console.Write(url);
return new Redirect(url);
}

GetTarget2方法:

public async Task<IEnumerable<Url>> GetTarget2(string hash)
{
var t2 = await _ctx.Url.Where(u => u.UrlShort == hash).ToArrayAsync();
return  t2;
}

以及实体:

[Table("Url")]
public class Url
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UrlShort { get; set; }
public string UrlOrigin { get; set; }
public string state { get; set; }
public int Customer_id { get; set; }
public int? targetItemId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ExpireAt { get; set; }
[JsonIgnore]
public List<Stats> GetStats { get; set; }
public Url()
{
}
public Url(int Id,string UrlShort,string UrlOrigin,string state,int Customer_id,DateTime CreatedAt,DateTime ExpireAt)
{
this.Id = Id;
this.UrlShort = UrlShort;
this.UrlOrigin = UrlOrigin;
this.state = state;
this.Customer_id = Customer_id;
this.CreatedAt = CreatedAt;
this.ExpireAt = ExpireAt;
}
}

当我试图传递数据库中的代码时,我得到的是:Not found,这意味着它在数据库中找不到它

更新:数据库上下文声明:

private readonly DatabaseContext _ctx; 

及其定义:

public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Url> Url { get; set; }
public DbSet<User> User { get; set; }
public DbSet<Stats> Stats { get; set; }
}

如果我正确理解了你的问题,那么你正试图通过从数据库中读取URL来重定向到另一个操作方法。如果转发的Url属于您的应用程序,并且只有动态参数,则可以尝试RedirectToAction方法进行重定向。

语法:

return RedirectToAction("ActionName", new { id = 90 });

将导致重定向到YourApp/Controller/ActionName/90

您只需要创建一个带参数的操作方法(如果需要(,并从另一个获取url的操作方法重定向。

另外,您也可以使用

return RedirectToAction("Index", new RouteValueDictionary( 
new { controller = "NameOfController", action = "Index", id = id } ) 
);

问题在于Redirect方法,该方法指示其内容为null或空,尽管我在终端中成功打印了url。所以我所做的是添加一个前缀(http://(,就像这个重定向("http://+url"(,url是来自数据库的url。如果url已经包含前缀http或https,我会在将其作为参数传递到Redirect方法之前将其删除。这样做解决了我的问题。

最新更新