如何在休息时检索请求的域URL?

时间:2012-04-13 05:39:24

标签: c# http rest

在Global.asax.cs文件中,我有允许跨域访问的代码。

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();

        if( // The requesting URL == "http://theproperdomain.com"){
            EnableCrossDmainAjaxCall();
        }
    }  

    private void EnableCrossDmainAjaxCall()
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }  

但在我的休息项目允许跨域访问之前,它必须首先检查请求域是否等于正确的域。即:“http://theproperdomain.com”

我有这段代码:

string properdomain = HttpContext.Current.Request.Url.AbsoluteUri;  

但我不确定它是否最好使用。
请建议你更好的主意。

修改

我的域名服务器是http://theproperdomain.com我的其他服务所在的位置 我将从我的webconfig中获取此域名,并与当前访问客户端进行比较。我需要这样做,因为我想只允许一个域进行“跨域访问”。

1 个答案:

答案 0 :(得分:1)

您可以使用Host header of HTTP/1.1标识当前请求发送到的域。根据规范,如果请求缺少此信息,您可以返回400 Bad Request

要访问标题,您可以使用HttpContext.Current.Request.Headers["HOST"]

但是,如果您想知道请求来自哪个应用程序,那么您需要维护一个应用程序机密,这对每个应用程序都是唯一的,需要授权。只要应用程序秘密仍然安全,这是安全的。避免使用引用标头,因为它是一个可选字段。