网址引荐来源网址在WebApi 2 MVC项目中不可用 [英] Url Referrer is not available in WebApi 2 MVC project

查看:226
本文介绍了网址引荐来源网址在WebApi 2 MVC项目中不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Controllers控制器的MVC WebAPI 2项目.我尝试调用的方法是POST(创建).我需要访问调用该方法的引用URL,无论我访问哪个对象,引用URL要么在对象中不存在,要么为空.

I have an MVC WebAPI 2 project with a Controllers controller. The Method I'm trying to call is POST (Create). I need to access the referring URL that called that method yet, no matter what object I access, the referring URL either doesn't exist in the object or is null.

例如,我添加了HTTPContext引用,以下返回null:

For example, I've added the HTTPContext reference and the following returns null:

var thingythingthing = HttpContext.Current.Request.UrlReferrer;

Request对象没有UrlReferrer属性.

这也返回null:

HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]

我无法修改标头,因为我需要能够生成该方法的链接并按调用的来源过滤访问.

I cannot modify the headers because I need to be able to generate a link to the method and filter access by origin of the call.

我应该去看看的任何特定地方,或者是为什么返回空值的任何特定原因?

Any particular place I should be look or, alternatively, any particular reason why those are returning null?

我有一个GET方法(HttpContext.Current.Request.RequestContext.HttpContext.Request.UrlReferrer)解决方案,但没有POST方法.

I have a solution for GET methods (HttpContext.Current.Request.RequestContext.HttpContext.Request.UrlReferrer) but not for POST methods.

推荐答案

请参见此答案.基本上,WebAPI请求使用另一种请求对象.但是,您可以创建一个扩展方法来为您提供UrlReferrer.从链接的答案中:

See this answer. Basically, WebAPI requests use a different kind of request object. You can create an extension method that provides a UrlReferrer for you, though. From the linked answer:

首先,您可以扩展HttpRequestMessage以提供UrlReferrer()方法:

First, you can extend HttpRequestMessage to provide a UrlReferrer() method:

public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}

然后您的客户需要将Referrer Header设置为其API Request:

Then your clients need to set the Referrer Header to their API Request:

// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

现在Web API Request包含引荐来源网址数据,您可以从Web API像这样访问引荐来源数据:

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();

这篇关于网址引荐来源网址在WebApi 2 MVC项目中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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