Please help to advise for my issue below.
I try to create an enrollment using sample code from here
private async Task<HttpResponseMessage> MakeRequest()
{
string path = #"<path_to_wav_file>";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<my_key>");
// Request parameters
queryString["shortAudio"] = "true";
queryString["identificationProfileId"] = "<my_profile_id>";
var uri = "https://westus.api.cognitive.microsoft.com/spid/v1.0/identificationProfiles/<my_profile_id>/enroll?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = File.ReadAllBytes(path);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
}
return response;
}
and got the response
{StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Pragma: no-cache
Operation-Location:
https://westus.api.cognitive.microsoft.com/spid/v1.0/operations/af54c843-8df9-4511-8d65-4825ebec024d
apim-request-id: 37567cff-d259-4a1d-82fc-9fc884edcfe3
Strict-Transport-Security: max-age=31536000; includeSubDomains;
preload x-content-type-options: nosniff Cache-Control: no-cache
Date: Tue, 08 Jan 2019 07:12:05 GMT X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET Content-Length: 0 Expires: -1 }}
said that
{"error":{"code":"Unspecified","message":"Access denied due to invalid
subscription key. Make sure you are subscribed to an API you are
trying to call and provide the right key."}}
The error message is strange because I used the same Subscription Key that created profile successfully.
I think you should use ("Ocp-Apim-Subscription-Key", "") when make request to
https://api.projectoxford.ai/spid/v1.0/operations/af54c843-8df9-4511-8d65-4825ebec024d
Related
This code:
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) })
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent("abc"), "token");
var response = await client.PostAsync("http://localhost", content);
var result = await response.Content.ReadAsStringAsync();
}
}
Generates the following HTTP request:
POST http://localhost/ HTTP/1.1
Host: localhost
Content-Type: multipart/form-data; boundary="4b39ed14-752b-480a-9846-fc0019132d15"
Content-Length: 174
--4b39ed14-752b-480a-9846-fc0019132d15
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=token
abc
--4b39ed14-752b-480a-9846-fc0019132d15--
We have a client who says their WAF is blocking the request because the name parameter should be quoted
Content-Disposition: form-data; name="token"
I have seen some differences in opinion on this:
https://github.com/akka/akka/issues/18788
https://github.com/akka/akka-http/issues/386
Does anyone know what is correct here?
I posted this to https://github.com/dotnet/runtime/issues/72447
Either form is correct, apparently
Short Version
I'm adding the response header:
Connection: keep-alive
but it's not in the resposne.
Long Version
I am trying to add a header to an HttpResponse in ASP.net:
public void ProcessRequest(HttpContext context)
{
context.Response.CacheControl = "no-cache";
context.Response.AppendHeader("Connection", "keep-alive");
context.Response.AppendHeader("AreTheseWorking", "yes");
context.Response.Flush();
}
And when the response comes back to the client (e.g. Chrome, Edge, Internet Explorer, Postman), the Connection header is missing:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1
Server: Microsoft-IIS/10.0
AreTheseWorking: yes
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 26 Feb 2022 16:29:17 GMT
What am I doing wrong?
Bonus Chatter
In addition to trying AppendHeader:
context.Response.AppendHeader("Connection", "keep-alive"); //preferred
I also tried AddHeader (which exists "for compatibility with earlier versions of ASP"):
context.Response.AddHeader("Connection", "keep-alive"); // legacy
I also tried Headers.Add:
context.Response.Headers.Add("Connection", "keep-alive"); //requires IIS 7 and integrated pipeline
What am i doing wrong?
Bonus: hypothetical motivation for the question
By default keep-alive is not allowed in ASP.net.
In order to allow it, you need to add an option to your web.config:
web.config:
<configuration>
<system.webServer>
<httpProtocol allowKeepAlive="true" />
</system.webServer>
</configuration>
This is especially important for Server-Send Events:
public void ProcessRequest(HttpContext context)
{
if (context.Request.AcceptTypes.Any("text/event-stream".Contains))
{
//Startup the HTTP Server Send Event - broadcasting values every 1 second.
SendSSE(context);
return;
}
}
private void SendSSE(HttpContext context)
{
//Don't worry about it.
string sessionId = context.Session.SessionID; //https://stackoverflow.com/a/1966562/12597
//Setup the response the way SSE needs to be
context.Response.ContentType = "text/event-stream";
context.Response.CacheControl = "no-cache";
context.Response.AppendHeader("Connection", "keep-alive");
context.Response.Flush();
while (context.Response.IsClientConnected)
{
System.Threading.Thread.Sleep(1000);
String data = DateTime.Now.ToString();
context.Response.Write("data: " + data + "\n\n");
context.Response.Flush();
}
}
I have a post controller in an MVC app returning this response:
return new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent("test")
};
When I hit the post URL with this code:
using (WebClient client = new WebClient())
{
string result = client.UploadString(url, content);
}
result contains this response:
StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Content-Type: text/plain; charset=utf-8 }
Why isn't "test" appearing after Content:?
Thanks!
You should not return HttpResponseMessage from ASP.NET MVC action. In this case you'll get messy response like this:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcZG90TmV0XE12Y0FwcGxpY2F0aW9u?=
X-Powered-By: ASP.NET
Date: Sun, 04 Feb 2018 10:18:38 GMT
Content-Length: 154
StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}
As you see, you actually get 200 HTTP response with HttpResponseMessage details in response body. This messy body content is what you deserialize into result variable.
ASP.NET MVC actions should return an instance of the class derived from System.Web.Mvc.ActionResult. Unfortunately, there is no built-in action result that allows setting both return status code and body content.
There is ContentResult class that allows to set return string content with status code of 200. There is also HttpStatusCodeResult that allows setting arbitrary status code but the response body will be empty.
But you could implement your custom action result with settable status code and response body. For simplicity, you could base it on ContentResult class. Here is a sample:
public class ContentResultEx : ContentResult
{
private readonly HttpStatusCode statusCode;
public ContentResultEx(HttpStatusCode statusCode, string message)
{
this.statusCode = statusCode;
Content = message;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
base.ExecuteResult(context);
HttpResponseBase response = context.HttpContext.Response;
response.StatusCode = (int)statusCode;
}
}
The action would look like:
public ActionResult SomeAction()
{
return new ContentResultEx(HttpStatusCode.Accepted, "test");
}
Another possible fix is to change your controller from MVC to WEB API controller. To make this - just change base class of controller from System.Web.Mvc.Controller to System.Web.Http.ApiController. In this case you could return HttpResponseMessage as in your answer.
In both cases you will get correct HTTP response with 202 status code and string in the body:
HTTP/1.1 202 Accepted
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcZG90TmV0XE12Y0FwcGxpY2F0aW9u?=
X-Powered-By: ASP.NET
Date: Sun, 04 Feb 2018 10:35:24 GMT
Content-Length: 4
test
I have one .net client which tries to make http request to web api service
here is my Request:
public List<Category> GetCategories()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54558/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Task<string> response = client.GetStringAsync("api/CategoryApi/");
List<Category> lstCategory = JsonConvert.DeserializeObjectAsync<List<Category>>(response.Result).Result;
return lstCategory;
}
public void Create(Category category)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var stringContent = new StringContent(category.ToString());
HttpResponseMessage responseMessage = client.PostAsync("api/CategoryApi/", stringContent).Result;
}
and in my webapi
public IEnumerable<Category> GetCategories()
{
return categoryRepository.data;
}
public string PostCategory(Category category)
{
categoryRepository.add(category);
return "MessageOk";
}
SO when I make request to my GetCategories action of the web-api everything is OK.
and no matter what I do it seems that .net application cannot find the Post action of the web-api and I never actually see entering in Postcategory method
as I have also put breakpoints here.
I only get the error
atusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNccG9zdGdyZXNcRGVza3RvcFxXZWJBcGlTZXJ2aWNlXFdlYkFwaVNlcnZpY2VcYXBpXENhdGVnb3J5QXBpXA==?=
Cache-Control: no-cache
Date: Sat, 13 Jun 2015 17:55:16 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 1022
Content-Type: application/json; charset=utf-8
Expires: -1
}}
What may be the issue. Thak you in advance
You are posting just a Category.ToString which if you didn't override ToString to be a Json or XML string, it will fail on the server side because there is no way to deserialize the content into a Category object. You should serialize the Category on the client before posting it. Also make sure your request headers include the proper Content-Type of application/json. By posting StringContent, the Content-Type won't be application/json. You are setting the Accept header, but that only describes the data coming back to your client, not the data you are posting. One last thing, I would not use the same HttpClient for both the get and the post request. Each method should use it's own HttpClient so you don't have any extra headers depending on the call.
I have an ASPX page that issues a Response.Redirect that points to an image file.
The redirect response headers look like this:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: https://www.site.com/folder/file.jpg
Server: Microsoft-IIS/8.0
Date: Tue, 29 Apr 2014 08:29:58 GMT
Content-Length: 241
Is it possible to force the client and any proxy servers to cache this response for say 30 days? Should I do this with Cache-Control, ETags or both? If so, how?
I have figured this out and tested it. The following code adds the ETags and cache-control:
protected void Page_Load(object sender, EventArgs e)
{
var absoluteUrl = GetUrlFromDatabase(Request["fileId"]);
CacheResponse(absoluteUrl);
Response.Redirect(absoluteUrl);
}
private static void CacheResponse(string absoluteLocation)
{
// you need to clear the headers that ASP.NET automatically adds
HttpContext.Current.Response.ClearHeaders();
// now get the etag (hash the
var etag = GetETag(absoluteLocation);
// see if the etag matches what was sent
var requestedETag = HttpContext.Current.Request.Headers["If-None-Match"];
if (requestedETag == etag)
{
HttpContext.Current.Response.Status = "304 Not Modified";
HttpContext.Current.ApplicationInstance.CompleteRequest();
return;
}
// otherwise set cacheability and etag.
HttpContext.Current.Response.Cache.SetValidUntilExpires(true);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMonths(1));
HttpContext.Current.Response.Cache.SetLastModified(DateTime.UtcNow);
HttpContext.Current.Response.Cache.SetETag("\"" + etag + "\"");
}
private static string GetETag(string url)
{
var guid = StringToGuid(url);
var etag = new ShortGuid(guid); // see reference to ShortGuid below
return etag.Value.Replace("-", string.Empty);
}
private static Guid StringToGuid(string value)
{
// Create a new instance of the MD5CryptoServiceProvider object.
var md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
return new Guid(data);
}
Reference: ShortGuid.
The initial HTTP response headers are now:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Expires: Thu, 29 May 2014 09:07:41 GMT
Last-Modified: Tue, 29 Apr 2014 09:07:41 GMT
ETag: "k28kbGNuxkWzP6gmLO2xQ"
Location: https://www.site.com/folder/file.jpg
Date: Tue, 29 Apr 2014 09:07:41 GMT
Content-Length: 241