Url Referrer is not available in WebApi 2 MVC project

最后都变了- 提交于 2019-12-22 09:40:15

问题


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.

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

var thingythingthing = HttpContext.Current.Request.UrlReferrer;

The Request object does not have a UrlReferrer property.

This returns null as well:

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?

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


回答1:


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:

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;
}

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

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

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

Request.UrlReferrer();


来源:https://stackoverflow.com/questions/38461688/url-referrer-is-not-available-in-webapi-2-mvc-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!