WepAPI Method is throwing MethodNotAllowed but I don't know why - c#

I think the answer is something simple, but I have a method throwing a 405 not allowed error and I'm not sure why. Before I get into details I'll point out something that seems like a clue - the method that works is actually called Get - and I'm not sure if there is some HTTP method mapping done behind the scenes that causes that to work.
I have a controller with multiple methods in it. So far I'm testing 2 of them and the first one works just fine, yet the second is throwing the error.
My controller is OOB setup, my logic and model are in separate projects. The following method is called and returns correctly:
[Route("api/GetFastPlan/{key}/{clientID}/{fastPlanID}")]
public RequestFastPlanResult Get(string key, string clientID, int fastPlanID)
{
return new FastPlanFileShare().RequestFastPlan(key, clientID, fastPlanID);
}
This method however is throwing a 405.
[Route("api/UpdateDownloads/{key}/{clientID}/{fastPlanID}")]
public UpdateDownloadsResult UpdateDownloads(string key
, string clientID, int fastPlanID)
{
return new FastPlanFileShare().UpdateNumberOfDownloadsColumnFastPlan(key
, clientID, fastPlanID);
}
I am calling them both with the same code setup, which is here in my test project:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:8129/api/UpdateDownloads/value1/value2/1082");
HttpResponseMessage response = httpClient.GetAsync("http://localhost:8129/api/UpdateDownloads/value1/value2/1082").Result;
Assert.IsTrue(response.IsSuccessStatusCode);
if (response.IsSuccessStatusCode)
{
var rp = response.Content.ReadAsAsync<ServiceReference2.RequestFastPlanResult>();
Assert.IsTrue(rp.Result.ServiceResult.WasSuccessful);
}
}
full error:
{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1,
Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache
X-SourceFiles:
=?UTF-8?B?RDpcUHJvamVjdHNcTkVUMjAxK1xFeWVNRCBFTVIgSW50ZXJuYWwgV2Vic2VydmljZXNcRU1SU2VydmljZXMuV2ViQVBJXGFwaVxVcGRhdGVEb3dubG9hZHNcZXllbWRlbXIjMVxFWUU5ODQ1NFwxMDgy?=
Cache-Control: no-cache Date: Wed, 06 Jan 2016 13:50:43 GMT
Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET Content-Length: 72 Allow: POST
Content-Type: application/json; charset=utf-8 Expires: -1 }}

Related

How to get a Empty http body using Unauthorized() in WebApi Core

I have a function in a webapi Core controller that returns an IActionResult. When I return Unauthorized(), get a http response message that includes contents in the body.
HTTP/1.1 401 Unauthorized
Transfer-Encoding: chunked
Content-Type: application/problem+json; charset=utf-8
Server: Microsoft-IIS/10.0
Request-Context: appId=cid-v1:bd2aaf31-7b2f-4d8e-b627-a27764a46523
X-Powered-By: ASP.NET
Date: Wed, 24 Mar 2021 02:14:55 GMT
a2
{"type":"https://tools.ietf.org/html/rfc7235#section-3.1","title":"Unauthorized","status":401,"traceId":"00-9d1f5fdb87116241a432f64d76ed8c35-8714a7bfa634c94f-00"}
0
How can I get it just to return a empty body like below as the web hook mechanism will error the messages if the body contains any value.
HTTP/1.1 401 Unauthorized
Transfer-Encoding: chunked
Server: Microsoft-IIS/10.0
Request-Context: appId=cid-v1:bd2aaf31-7b2f-4d8e-b627-a27764a46523
X-Powered-By: ASP.NET
Date: Wed, 24 Mar 2021 02:14:55 GMT
0
The code looks like
[Route("api/[controller]")]
[ApiController]
public classTestController : ControllerBase
{
[HttpPost("webhook")]
public IActionResult Post()
{
if (<some test>))
{
return Unauthorized();
}
// do something
return Ok();
}
}

Salesforce marketing cloud API does not return an access/authorization token

I have an application that requests the marketing cloud for an access token to use in subsequent requests to access the API. This was designed last year and working fine till last week. The same request has been failing since 02/22. Here is the sample code to request the token:
public static async Task<string> GetAuthorizationToken(string ClientId, string ClientSecret)
{
string strAuthorizationToken = string.Empty;
HttpClient client = new HttpClient();
var dictParams = new Dictionary<string, string>()
{
{ "clientId", ClientId }, {"clientSecret", ClientSecret }
};
var content = new FormUrlEncodedContent(dictParams);
var response = await client.PostAsync("https://auth.exacttargetapis.com/v1/requestToken", content);
if (response.IsSuccessStatusCode)
{
var strresponse = await response.Content.ReadAsStringAsync();
//dynamic objResult = JsonConvert.DeserializeObject<dynamic>(strresponse);
//strAuthorizationToken = objResult.accessToken;
}
return strAuthorizationToken;
}
GetAuthorizationToken("*********", "*******").GetAwaiter().GetResult();
Here is the error I am getting from the API:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Mashery-Responder: 02-26
Vary: Origin
X-Mashery-Message-ID: f4cec199-2e7e-49e2-88e0-6673ffe849ed
strict-transport-security: max-age=15552000; preload
Content-Security-Policy: upgrade-insecure-requests
x-xss-protection: 1; mode=block
x-frame-options: DENY
x-content-type-options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Connection: close
Cache-Control: no-store, must-revalidate, no-cache, max-age=0, private
Date: Tue, 26 Feb 2019 16:42:29 GMT
Server: Apache
Content-Length: 223
Content-Type: application/json; charset=UTF-8
}}
I need to know what has been changed or what I need to fix in this code to be able to access the API again. Please help how I can make this work again.
Thanks in advance.
I am posting the answer as it is resolved and might be helpful for someone else who has a similar issue with sending http requests.
I had to add the following line of code to specify the security protocol to use:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

Using UCWA api and getting error when trying to connect through code C#

I am using UCWA api to create Lync Meeting URL but I am getting error in a step,
and it is related to LYNC so trying to figure out how to resolve. My code is
string url_00 = ucwaMsRtcOAuth;
var authDic_00 = new Dictionary<string, string>();
authDic_00.Add("grant_type", "password");
authDic_00.Add("username", String.Format("{0}\\{1}", ucwaAdDomain, ucwaAdUser));
authDic_00.Add("password", ucwaAdPassword);
httpClient.DefaultRequestHeaders.Remove("Accept");
httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.microsoft.com.ucwa+xml");
var res_00 = await httpClient.PostAsync(url_00, new FormUrlEncodedContent(authDic_00));
string res_00_request = res_00.RequestMessage.ToString();
string res_00_headers = res_00.Headers.ToString();
string res_00_status = res_00.StatusCode.ToString();
var res_00_content = await res_00.Content.ReadAsStringAsync();
and output of last 4 variable is as
res_00.RequestMessage
Method: POST, RequestUri: 'https://lynceu1webint.MYCOMPANYNAME.com/WebTicket/oauthtoken',
Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
Accept: application/vnd.microsoft.com.ucwa+xml
Content-Type: application/x-www-form-urlencoded
Content-Length: 72
}
res_00.Headers
Pragma: no-cache
X-Ms-diagnostics: 28020;source="GDLYNPRFEWP01P.corp.MYCOMPANYNAME.com";reason="No valid security token."
X-MS-Server-Fqdn: GDLYNPRFEWP01P.corp.MYCOMPANYNAME.com
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Cache-Control: no-store
Date: Fri, 20 May 2016 11:12:09 GMT
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
res_00.StatusCode
BadRequest
res_00.Content
{"error":"invalid_grant"}
There are a few potential reasons you are seeing that error response:
Incorrect domain\username combo
Incorrect password
Incorrect grant string
If you are intending to use domain and password with the password grant_type make sure your grant string resembles:
grant_type=password&domain\username&password=*******
If that still does not work you may be required to provide the SIP/Account used to login in that user to the desktop version of Skype for Business. This grant string would look like:
grant_type=password&username#domain.com&password=*******

HttpClient.SendAsync: 500 - Internal Server Error in Windows Service Application

I am seeing the following message in attempting to post a json string to a web API (this is what is written to file in the line containing System.IO.File.WriteAllText):
Response: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Cache-Control: no-cache
Date: Thu, 13 Aug 2015 21:26:12 GMT
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 36
Content-Type: application/json; charset=utf-8
Expires: -1
}
The code within my async posting method is as follows:
Uri theUri = new Uri("http://www.website.com/WebsiteAPI/PostDetails");
HttpClient aClient = new HttpClient();
aClient.BaseAddress = theUri;
aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
aClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "USERNAME", "PASSWORD"))));
aClient.DefaultRequestHeaders.Host = theUri.Host;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, theUri);
request.Content = new StringContent(resource, Encoding.UTF8, "application/json");
// Post the data
aClient.SendAsync(request).ContinueWith(responseTask =>
{
System.IO.File.WriteAllText(PROFILE_JSON_PATH, "Response: " + responseTask.Result);
});
I've tried many different solutions online but nothing seems to work. Any idea why this may not be working?
The short answer is that there is something with your Web API that is erroring. You may or may not have something wrong with your client code--but you'll have to go to the Web API for information that could explain what the problem is.

How can I get a full control over the HTTP headers in ASP.Net WebAPI 2?

The default behavior of using HttpResponseMessage as a return type for the Get action looks like the following:
HTTP/1.1 200 OK
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
<my data>
What I want is to have a full control over which http header to be in the response.
Default Get method in an ApiController class:
[HttpGet]
public HttpResponseMessage Ping()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("X-Custom-Header", "This is my custom header.");
response.Headers.Remove("Server");
return response;
}

Categories