Invoking another URL - c#

string url = "http://foo.com/bar?id=" + id + "&more=" + more;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
I m trying make a call to another server, and getting back the following:
|FATAL|The remote server returned an error: (406) Not Acceptable. (REF #1)
System.Net.WebException: The remote server returned an error: (406) Not Acceptable.
Why am i getting this error? and how to fix this?

According to the RFC
10.4.7 406 Not Acceptable
The resource identified by the request
is only capable of generating response
entities which have content
characteristics not acceptable
according to the accept headers sent
in the request.
Review the accept headers that your request is sending , and the content server in that URL ; )
BONUS
To see the accept headers: browse to
the URL and use FireBug (HTML tab).
To set the accept headers into your
request use the HttpWebRequest
Members.

Related

C# WebClient using UploadString to call HttpPost method from an ApiController also in C#. 415 or 400 error

I want in C# to call an ApiController also in C# but I'm getting error 415 or 400 when uploading the Json using the UploadString method from the WebClient instance.
The server code is the auto-generated call TestController. The file is exactly how Visual Studio 2019 generate it.
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// POST: api/Test
[HttpPost]
public void Post([FromBody] string value)
{
}
...
}
The client code look like that:
WebClient client = new WebClient();
client.UploadString("https://localhost:44345/api/Test", "ABC"); // Edit: "ABC" is not a valid JSON
I'm getting
System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'
So after googling, most suggest is the ContentType not getting specify, if I add
client.Headers[HttpRequestHeader.ContentType] = "application/json";
I get System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'
Any clue?
Seems like the problem is related to the POST/PUT/PATCH... if I do the GET, it's working and returning me the sample data ["value1","value2"]
Edit: I'm not stick to using WebClient.UploadString method but I would like a solution that doesn't involved 25 lines of custom code... I means I can't believe it's that hard where you can do it in jQuery using a single line.
I'm getting
System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'
When you use [FromBody], the Content-Type header is used in order to determine how to parse the request body. When Content-Type isn't specified, the model-binding process doesn't know how to consume the body and therefore returns a 415.
I get System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'
By setting the Content-Type header to application/json, you're instructing the model-binding process to treat the data as JSON, but ABC itself isn't valid JSON. If you just want to send a JSON-encoded string, you can also wrap the value in quotes, like this:
client.UploadString("https://localhost:44345/api/Test", "\"ABC\"");
"ABC" is a valid JSON string and will be accepted by your ASP.NET Core API.
Simple Solution:
Specify Content-type in header while calling the API,
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "text/json");
client.UploadString("https://localhost:44345/api/Test", "\"ABC\"");
Edit:
Don't use [From_Body] attribute as it has terrible error handling capability,
see Here.
If request body has any invalid input(syntax error,unsupported input) then it'll throw 400 and 415 for bad request and unsupported content. for the same reason it may take null as input from the request body it it doesn't understand the format.
So, remove the attribute and try uploading the string in plain format as it accept only String and you doesn't required to specify the Content-Type attribute while making the request.
[HttpPost]
public void Post(string value)
{
}
And call it like how you were calling in your original post.
WebClient client = new WebClient();
client.UploadString("https://localhost:44345/api/Test", "ABC");

c# using TinyUrl Api(getting original address from shortened address)

i found the tinyurl api to shorten the Url. you can see from the link below.
https://blogs.msdn.microsoft.com/bramveen/2009/01/06/converting-url-to-tinyurl-in-c/
And I also want to get original address from my shortened url.
but i can't find that reverse api.
anyone knows how to reverse it?
Looking at the api there is no api to get the reverse. But all tinyurl is doing when you send a HTTP request to tiny url is return a HTTP 301 with the original url in the Location response header. So you could do something like this.
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Now you can use the response object to read the location header value (which is your original url).

WCF Service - HTTP Request and Response

I have 2 WCF services:
1. Inbound - the client calls this service.
2. Outbound - we send information to client.
We now know that the response from client will be in default http response for outbound, and they want us to send a default http response for inbound.
Right now, I have specified the response object as a class. How do I implement http response?, how can I manage my services to send a http response?.
I have tried to search around but I am not getting any starter links for this.
Could you please guide me in the right direction?
What should my response object look like in this case?
I solved my issue with this:
To set the response object with the value:
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
To retrieve the value I used this:
int statuscode = HttpContext.Current.Response.StatusCode;
string description = HttpContext.Current.Response.StatusDescription;

Creating directory on server using HttpWebRequest

I am trying to create directory on server via https. But while returning the response it generates exceptions: “The remote server returned an error: (404) Not Found.”
The code is as follows:
string szURL3 = #"https://directoryurl/TestDir/";
//Create an HTTP request for the URL.
HttpWebRequest httpMkColRequest = (HttpWebRequest)WebRequest.Create(szURL3);
// Set up new credentials.
httpMkColRequest.Credentials = new NetworkCredential(_httpsUserName, _httpsPassword);
// Pre-authenticate the request.
httpMkColRequest.PreAuthenticate = true;
// Define the HTTP method.
httpMkColRequest.Method = #"MKCOL";
// Retrieve the response.
HttpWebResponse httpMkColResponse = (HttpWebResponse)httpMkColRequest.GetResponse();
//Write the response status to the console.
Console.WriteLine(#"MKCOL Response: {0}",httpMkColResponse.StatusDescription);
Could anybody support regarding this. I am able to get the directory information correctly in the same way. As I referred some links:
http://blogs.msdn.com/b/robert_mcmurray/archive/2011/10/18/sending-webdav-requests-in-net-revisited.aspx
According to this, what I understood is that the resources are locked. But how to unlock the resources for creating directory.
Please correct where modification required.
I solved the issue. The webDAV Configuration on the server was not enabled.

How to simulate browser HTTP POST request and capture result in C#

Lets say we have a web page with a search input form, which submits data to server via HTTP GET. So that's mean server receive search data through query strings. User can see the URL and can also initialize this request by himself (via URL + Query strings).
We all know that. Here is the question.
What if this web page submits data to the server via HTTP POST? How can user initialize this request by himself?
Well I know how to capture HTTP POST (that's why network sniffers are for), but how can I simulate this HTTP POST request by myself in a C# code?
You could take a look at the WebClient class. It allows you to post data to an arbitrary url:
using (var client = new WebClient())
{
var dataToPost = Encoding.Default.GetBytes("param1=value1&param2=value2");
var result = client.UploadData("http://example.com", "POST", dataToPost);
// do something with the result
}
Will generate the following request:
POST / HTTP/1.1
Host: example.com
Content-Length: 27
Expect: 100-continue
Connection: Keep-Alive
param1=value1&param2=value2

Categories