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
Related
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
I'd like to have an ApiController with a controller action that accepts POST requests and has a name that starts with Delete. I'm using the following jQuery:
function DeleteMyDomainObjectButton_OnClick() {
var $div = $(this).closest("div.domain-object");
var url = baseUrl + "Api/MyBusiness/DeleteMyDomainObject";
var dto = {
"MyDomainObjectId": $div.find("input[name=MyDomainObjectId]").val()
};
$.ajax({
complete: DeleteMyDomainObjectAjax_OnComplete
, dataType: "json"
, contentType: "application/json"
, accept: "applcation/json"
, data: JSON.stringify(dto)
, error: DeleteMyDomainObjectAjax_OnError
, method: "POST"
, success: DeleteMyDomainObjectAjax_OnSuccess
, url: url
});
}
I keep getting a 405: {"Message":"The requested resource does not support http method 'POST'."}. The response headers are:
HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: DELETE
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 07 Jul 2015 20:45:35 GMT
Content-Length: 73
I did check the request headers, and it actually is sending a POST. Here's my controller:
public class BaseApiController : ApiController
{
/* Properties for All API Controllers set by DI */
}
public class MyBusinessController : BaseApiController
{
public virtual MyDomainObject FooBar(DeleteMyDomainObjectDto dto)
{
return this.DeleteMyDomainObject(p_input);
}
[HttpPost] // Doesn't work.
// [AcceptVerbs(HttpVerbs.Post)] // Also doesn't work.
public virtual MyDomainObject DeleteMyDomainObject(DeleteMyDomainObjectDto dto)
{
return BusinessLogic.DeleteMyDomainObject(dto)
}
}
Now, if I change the controller action that I reference from jQuery to FooBar, it works.
Question: How can I turn off the magic sauce that makes the ApiController only allow DELETE requests for controller actions with names starting with the string Delete? Or am I doing something else wrong?
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
My web app generates a CSV file on the fly, but whenever I use GZIP compression, the download fails:
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0,no-store, no-cache
Transfer-Encoding: chunked
Content-Type: text/csv;charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
Content-Disposition: attachment;filename="filename.csv"
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
p3p: CP="CAO PSA OUR"
Date: Fri, 03 Feb 2012 11:27:27 GMT
The download appears as "Interrupted" in Google Chrome, and in Internet Explorer appears an error that says "Content decoding has failed" .
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0,no-store, no-cache
Transfer-Encoding: chunked
Content-Type: text/csv;charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
Content-Disposition: attachment;filename="filename.csv"
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
p3p: CP="CAO PSA OUR"
Date: Fri, 03 Feb 2012 11:23:30 GMT
The solution is disabling compression on that action, but... why does this happen?
Cheers.
UPDATE: The compression filter that I use:
public class EnableCompressionAttribute : ActionFilterAttribute
{
const CompressionMode compress = CompressionMode.Compress;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction)
return;
var actionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
if (actionAttributes != null && actionAttributes.Any(attr => attr is SkipCompressionAttribute))
return;
HttpRequestBase request = filterContext.HttpContext.Request;
HttpResponseBase response = filterContext.HttpContext.Response;
String acceptEncoding = request.Headers["Accept-Encoding"];
if (acceptEncoding == null || response.Filter == null)
return;
if (acceptEncoding.ToLower().Contains("gzip"))
{
response.Filter = new GZipStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "gzip");
response.AppendHeader("Vary", "Accept-Encoding");
}
else if (acceptEncoding.ToLower().Contains("deflate"))
{
response.Filter = new DeflateStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "deflate");
response.AppendHeader("Vary", "Accept-Encoding");
}
}
}
Try:
Response.Headers.Remove("Content-Encoding");
Response.AppendHeader("Content-Encoding", "gzip");
Another problem may be the caching: what if a client accepts compressed content, but the next client doesn't, and the server cached the compressed data? what the second client will get? A cached compressed page that won't decode!
To fix that, add another method:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "GZIP")
{
string acceptEncoding = HttpContext.Current.Response.Headers["Content-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
return "";
else if (acceptEncoding.Contains("gzip"))
return "GZIP";
else if (acceptEncoding.Contains("deflate"))
return "DEFLATE";
return "";
}
return base.GetVaryByCustomString(context, custom);
}