我有一個內置于 .NET 的 web api,在一個端點內,我想重定向到一個與插入到資料庫中的代碼相匹配的 url。端點將代碼作為入口,我應該重定向到相應的 url。為此,我使用了實際上不起作用的重定向方法。如果 url 為空或空但它存在,我做了 Console.Write 來列印。這是我的控制器的代碼:
[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; }
}
uj5u.com熱心網友回復:
如果我正確理解了您的問題,那么您正在嘗試通過從資料庫中讀取 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 } )
);
uj5u.com熱心網友回復:
問題是 Redirect 方法指示其內容為空或空,盡管我在終端中成功列印了 url。所以我所做的是添加一個前綴(http://)像這樣重定向(“http://” url),url是來自資料庫的url。如果 url 已經包含前綴 http 或 https,我會在將其作為引數傳遞給 Redirect 方法之前將其洗掉。這樣做解決了我的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388594.html
下一篇:從不安全和固定的屬性回傳跨度
