如何从 Referrer Uri 获取 Controller 和 Action 名称? [英] How do I get the Controller and Action names from the Referrer Uri?

查看:18
本文介绍了如何从 Referrer Uri 获取 Controller 和 Action 名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于从控制器和操作名称构建 Uris 的信息,但我该如何反过来呢?

There's a lot of information for building Uris from Controller and Action names, but how can I do this the other way around?

基本上,我想要实现的只是从引用页面(即 Request.UrlReferrer)获取控制器和操作名称.有没有简单的方法来实现这一目标?

Basically, all I'm trying to achieve is to get the Controller and Action names from the referring page (i.e. Request.UrlReferrer). Is there an easy way to achieve this?

推荐答案

我认为这应该可以解决问题:

I think this should do the trick:

// Split the url to url + query string
var fullUrl = Request.UrlReferrer.ToString();
var questionMarkIndex = fullUrl.IndexOf('?');
string queryString = null;
string url = fullUrl;
if (questionMarkIndex != -1) // There is a QueryString
{    
    url = fullUrl.Substring(0, questionMarkIndex); 
    queryString = fullUrl.Substring(questionMarkIndex + 1);
}   

// Arranges
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response)

var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

// Extract the data    
var values = routeData.Values;
var controllerName = values["controller"];
var actionName = values["action"];
var areaName = values["area"];

我的 Visual Studio 目前已关闭,因此我无法对其进行测试,但它应该可以按预期工作.

My Visual Studio is currently down so I could not test it, but it should work as expected.

这篇关于如何从 Referrer Uri 获取 Controller 和 Action 名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆