HttpRequest.UrlReferrer does not appear to exist - c#

I have a web application which uses MVC4, but now realised it really should be a Web API and as such I'm moving over to a ASP.NET 4.5.2 web API 2 project.
The problem is, where I was using Request.ServerVariables[] in my MVC project I have been advised that it's not the 'correct' way in a Web API, as such, I should be using Request.RequestUrl
The example on the MSDN is simply
Uri MyUrl = Request.UrlReferrer; //kaboom for me
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>");
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>");
The issue is, despite referencing System.Web there is no property for Request are UrlReferrer - the only properties are Content, Headers, Method, Properties, RequestUri and Version.
Why can't I use Request.UrlReferrer as per the MSDN example?

I suspect you just need to get the current request in a different way, due to being in a static method rather than in a context where you can refer to a Request instance property:
var request = HttpContext.Current;
var referrer = request.UrlReferrer;
...

Related

Setting Authorization Header to .Net Web Service Client

I know this has been asked a hundred times before, but I just can't get this working. I have a .Net web service client that needs to connect to an external web service that does not return 401 challenge response. I have to send the authentication header on the first call. I have overridden the GetWebRequest method of the generated proxy class by creating a partial class in another file. I have also added the method to the generated file to see if that makes a difference, but the code just does not get called. This was originally a .Net 3.5 Web Service Project created in VS 2013, but I have tried changing the target framework to 4.0, 4.5 e.t.c. and that does not have any effect.
The code I am using:
[System.Web.Services.WebServiceBindingAttribute(Name = "WSLDSD03_v1_webService_ValidationTicketCreation_Binder", Namespace = "http://llvap002d/WSLDSD03.v1.webService:ValidationTicketCreation")]
public partial class WSLDSD03_v1_webService_ValidationTicketCreation_Binder : System.Web.Services.Protocols.SoapHttpClientProtocol
{
protected override WebRequest GetWebRequest(Uri uri)
{
var request = base.GetWebRequest(uri);
string WSUID = ConfigurationManager.AppSettings["WSUID"];
string WSPWD = ConfigurationManager.AppSettings["WSPWD"];
string encoded = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(WSUID + ":" + WSPWD));
request.Headers.Add("Authorization", "Basic " + encoded);
return request;
}
}
Update: I have since found that after a clean solution and rebuild the method does in fact get called if I move it into the generated class. It is the partial class in a separate file that appears to be the problem.
It turned out to be a simple coding error. I failed to notice that the namespace in the generated proxy file was like MyProject.WebReference, but in my separate file I used the main project namespace.

Sharepoint REST set metadata after document upload

I have a C# console application (which will ultimately be a windows service when it's finished). The purpose is to migrate a document store (500k+ documents) over to SharePoint 2013.
Note, this is a standalone C# app that will run on a server that does not have SharePoint installed. I am using pure REST via HttpClient calls.
Uploading a document and setting its metadata has 3 steps:
Upload the document (POST)
e.g. baseURL + "web/" + "GetFolderByServerRelativeUrl('/sites" + libPath + "')/Files/Add(url='" + filename + "',overwrite=true)";
Retrieve details for the list item associated with this document (GET)
e.g. baseURL + "web/lists/getbytitle('" + docLibName + "')/items?$filter=Title eq '" + filenameNoExt + "'"
These first 2 steps are working fine.
Update the metadata
This is the bit that's causing me sleepless nights now. I can't seem to figure out what exactly I should be sending to the web service, and anything I try just gives errors. I can't find any examples of anyone who's tried to do this; and the MS documentation is very sparse.
The MS documentation from http://msdn.microsoft.com/en-us/library/office/dn292552%28v=office.15%29.aspx says:
The following example shows how to update a list by using the MERGE method.
url: http: //siteurl/_api/web/lists(guid'list GUID')
method: POST
body: { '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }
Headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
IF-MATCH": etag or "*"
X-HTTP-Method: MERGE,
accept: "application/json;odata=verbose"
content-type: "application/json;odata=verbose"
content-length:length of post body
In my application, I have set the type in the query to SP.Data.CertificatesItem, which is what was returned in step 2; and I'm trying to set the Certificate Type field to the specified value, rather than the document title:
string body = "{ '__metadata': { 'type': '" + spItemType + "' }, 'CertificateType': 'Medical Certificate'}";
(there are several fields which need to be set; I am just hard-coding one field here for testing purposes. The fields which need to be set depend on the content type of the document library.)
Additionally, the URL is slightly different. Where the example had:
http: //siteurl/_api/web/lists(guid'list GUID')
I have (specific example, slightly anonymized):
http: //siteurl/_api/Web/Lists(guid'cdcbef76-8bc0-4a68-9279-f6f3b6cbd3c3')/Items(2)
Otherwise, my call is identical to the example above.
I am getting the error message:
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The parameter __metadata does not exist in method GetById."}}}
I don't understand what I'm doing wrong! And I can't find any concrete examples anywhere.
From the page: http://msdn.microsoft.com/en-us/library/office/dn292553%28v=office.15%29.aspx :
If you want to update a file's metadata, you'll have to construct an endpoint that reaches the file as a list item. You can do this because each folder is also a list, and each file is also a list item. Construct an endpoint that looks like this: https: //siteurl/_api/web/lists/getbytitle('Documents')/items(). Working with lists and list items with REST explains how to update a list item's metadata.
Can anyone provide any insight here?
UPDATE:
Seems the X-HTTP-Method wasn't getting set correctly. I fixed that, now I'm getting:
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartObject' node was expected."}}}
I came across your question while looking into this myself. I have documented how to do file uploads, creating, updating and retrieving list items including those with Termstore data all in .NET using the HttpClient with no JQuery required.
Example for updating a file from the HttpClient using REST:
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
HttpContent strContent = new StringContent(String.Concat("{ '__metadata': { 'type': 'SP.List' }, 'Title': '", filename, "' }"));
strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
HttpResponseMessage updateResponse = await client.PostAsync(String.Concat("_api/web/lists/GetByTitle('Project Photos')/Items(", id, ")"), strContent);
updateResponse.EnsureSuccessStatusCode();
if (updateResponse.IsSuccessStatusCode)
{}
https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
Hopefully this helps.
Arcan.NET

sending mail from outside of a website or asp.net application

is it possible to post data from an html page using Jquery to another asp.net website ?
say www.site1.com/mail.html - > www.site2.com/mailServ.aspx
using jquery ajax i could use this code to post to code behind [webmethod]
so instead of code within same website(site2) it will be sent from site1
this is the code i am using to post the form data to a web method within same website application
function jQuerySendMailCsCodeBehind(resluts) {
var SentClientinfo = []
SentClientinfo.push({ key: "SentClientinfo", value: resluts });
var CurrpageURL = "default.aspx/"; <---
var WebmethodName = "StartTest";
var StageIdentifyer = "stage1";
var Post_TargetUrl = CurrpageURL + WebmethodName;
jQueryAajaxNoPostBack(Post_TargetUrl, SentClientinfo, StageIdentifyer);
}
i tried to post from outside of application
so i just used
var CurrpageURL = "http://www.site2.com/default.aspx/";
from the other site (site1) html website non asp.net but the idea did not work in reality (:
so is there an option that a webForms application/ asp.net website
will accept requests from another website code of ajax/jquery ?
By default, JavaScript is not allowed to access other domains than the one it originated from for security reasons. You don't want the JavaScripts on my site to access your bank's web site, with your bank login cookie if you happen to be looking at my site while being logged in to the bank.
One way to work around it is JsonP, but as far as I've understood it it's mostly for retrieving data.
What you're probably looking for is Cross Origin Resource Sharing or short CORS. To implement that, your site2 would need to set a Access-Control-Allow-Origin header and the users would be required to use a browser that supports CORS (not all do, see the wikipedia page for info).
You cannot make cross-website requests with javascript. You need to use jsonp
jQuery supports jsonp, see the following example
$.ajax({
type: 'GET',
url: 'http://githubbadge.appspot.com/badge/torvalds',
dataType: 'jsonp',
success: function(json) {
var result = '<h3>' + json.user.login + '</h3>' +
'<p>Languages: ' + json.languages + '</p>' +
'<p>Followers: ' + json.user.followers + '</p>';
$('#badge').append(result);
}
});

Failing to retrieve access token in .NET desktop app

I'm writing a .NET app that runs on a Windows computer. It is not accessible through the browser. The problem is, I can't authenticate like I should. I'm currently coding in C# .NET, more specific in C#.
I have a webbrowser control on my form.
The user logs on to facebook through this webbrowser control.
After the logon, I start the authentication procedure.
I then retreive a code.
Here's where it goes wrong. With this code I want to obtain an access token.
The generated request URL looks like: https://graph.facebook.com/oauth/access_token?client_id=____MY_APP_ID______&redirect_uri=http://localhost/&client_secret=_____MY_APP_SECRET_____&code=____MY_RETREIVED_CODE_____ and is made through the code below.
Please note that my redirect URL is http://localhost. This should be okay, right?
Also, in my App Settings, I have the following information.
Site URL: http://localhost/
Site Domain: localhost
private String ExchangeCodeForToken(String code, Uri redirectUrl)
{
var TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token");
var url = TokenEndpoint + "?" +
"client_id=" + _AppID + "&" +
"redirect_uri=" + redirectUrl + "&" +
"client_secret=" + _AppSecret + "&" +
"code=" + code;
var request = WebRequest.CreateDefault(new Uri(url));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var responseReader = new StreamReader(responseStream))
{
var responseText = responseReader.ReadToEnd();
var token = responseText.Replace("access_token=", "");
return token;
}
}
}
}
When I execute this, I get this error:
error http://www.imageupload.org/getfile.php?id=50131&a=447f6fcc0ebd4d3f8e8a59a3a6e36ac3&t=4de0841c&o=0889D68FDC35508BA2C6F2689FCBAB7C30A8670CC9647EE598701D8BEC13ED278F0989D393&n=autherror.png&i=1
Webexception was unhandled by user code
The remote server returned an error: (400) Bad Request.
Here's where I think I might be going wrong:
Are my app settings correct?
Should my redirect url be http://localhost, even if there isn't actually a service listening there?
Most importantly:
how do I get rid of this error and retreive the access token?
Thanks in advance!
You get this error because you are not supposed to call this URL from a Desktop app : as far as I know, you can not use the token endpoint for Desktop app authentication. Also, you can get the access token directly (no need to ask for a code first). Here is what you have to do.
Load the following URL in your embedded web browser :
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&
redirect_uri=https://www.facebook.com/connect/login_success.html
The user will be asked to log in and will be redirected to this URL with the access token in the URL :
https://www.facebook.com/connect/login_success.html#access_token=...
So you have to detect the redirect and retrieve the access token from the URL.
Thanks quinten!
However, I've managed to solve my own problem by using the C# Facebook SDK.
This software development kit has been a really great help!
There are a lot of samples included (including authorisation)
Anyone who programs in .NET with facebook should check it out! Coding for facebook is now much easier.
http://facebooksdk.codeplex.com/

Getting the HTTP Referrer in ASP.NET

I'm looking for a quick, easy and reliable way of getting the browser's HTTP Referrer in ASP.Net (C#). I know the HTTP Referrer itself is unreliable, but I do want a reliable way of getting the referrer if it is present.
You could use the UrlReferrer property of the current request:
Request.UrlReferrer
This will read the Referer HTTP header from the request which may or may not be supplied by the client (user agent).
Request.Headers["Referer"]
Explanation
The Request.UrlReferrer property will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).
Therefore, the Request.UrlReferrer property is not 100% reliable - it may contain data that cannot be parsed into a Uri class. To ensure the value is always readable, use Request.Headers["Referer"] instead.
As for using Request.ServerVariables as others here have suggested, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
Request.Headers is a better choice than Request.ServerVariables, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.
So the most reliable solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.
Use the Request.UrlReferrer property.
Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.
Like this: HttpRequest.UrlReferrer Property
Uri myReferrer = Request.UrlReferrer;
string actual = myReferrer.ToString();
I'm using .Net Core 2 mvc,
this one work for me ( to get the previews page) :
HttpContext.Request.Headers["Referer"];
Since Google takes you to this post when searching for C# Web API Referrer here's the deal: Web API uses a different type of Request from normal MVC Request called HttpRequestMessage which does not include UrlReferrer. Since a normal Web API request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object, a better way is to use Headers.
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();
string referrer = HttpContext.Current.Request.UrlReferrer.ToString();
Sometime you must to give all the link like this
System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
(in option when "Current" not founded)
Using .NET Core or .NET 5 I would recommend this:
httpContext.Request.Headers.TryGetValue("Referer", out var refererHeader)
Belonging to other reply, I have added condition clause for getting null.
string ComingUrl = "";
if (Request.UrlReferrer != null)
{
ComingUrl = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
}
else
{
ComingUrl = "Direct"; // Your code
}

Categories