I have a request object.
I tried doing
var str;
for (var i in this.request)
{
str += i + "\n";
}
And got:
headers
params
response
getClass
equals
query
class
hashCode
wait
uri
pause
resume
endHandler
bodyHandler
notify
path
dataHandler
method
toString
exceptionHandler
notifyAll
Post parameters are nowhere to be found. Can anyone shed some light into this mistery ?
params() and headers() don't contain anything.
Use a bodyHandler (here assuming you're posting JSON):
req.bodyHandler(function(data) {
var postData = JSON.parse(data.toString());
});
This can be done using the formAttributes on the http request. Here is an example in scala
req.expectMultiPart(true) //Will expect a form
req.endHandler({
req.formAttributes() //This is used to access form attributes
//some code with attributes
})
Reference: http://vertx.io/core_manual_java.html#handling-multipart-form-attributes
Related
I tried to call serenity endpoint list function from a third party console application but it is returning System.InvalidOperationException: Incorrect Content-Type error. Do i need to change something on my endpoint? By the way I am able to successfully call the Account/Login function.
Below is my API function in serenity endpoint. Even though when running this api in web browser the same error I am getting "System.InvalidOperationException: Incorrect Content-Type"
public ActionResult GetQuotes(IDbConnection connection, ListRequest request) {
var entities = new List<Object>();
var repos = new MyRepository();
var listResponse = repos.List(connection, request);
foreach (var e in listResponse.Entities)
{
var fields = new List<Object>();
foreach (var f in e.GetFields())
{
fields.Add(e.GetType().GetProperty(f.PropertyName).GetValue(e));
}
entities.Add(fields);
}
return Json(entities);
}
content type seems like empty. It's must be application/json. check requests from chrome developer tools network tab. you can see your content type there. For serenity, default content type is already application/json, you don't need to do any changes about that.
If one omits the Accept header in a request to an Asp.Net web API the server will return (415) Unsupported Media Type
I am looking for a way to force the API to assume a default return type (in my case, application/json) when the request does not contain an Accept value in its headers.
After a substantial amount of reading and searching, I'm not sure this is even possible?
You can force the framework to use XML formatter when HTTP Accept header is missing, by doing the following trick:
var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(jsonFormatter);
This way the JSON formatter will be the second registered formatter in the list, and the XML will be the first one.
This is content negotiator resposibility to choose the right formatter to serialize the response object. But by default WebApi framework gets JsonFormatter if could not find appropriate formatter.
If there are still no matches, the content negotiator simply picks the first formatter that can serialize the type.
So it is strange behavior. Anyway you could set up custom content negotiator to choose explicit JsonFormatter if request does not have Accept header.
public class JsonContentNegotiator : DefaultContentNegotiator
{
protected override MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)
{
var defaultMatch = base.MatchAcceptHeader(sortedAcceptValues, formatter);
if (defaultMatch == null)
{
//Check to find json formatter
var jsonMediaType = formatter.SupportedMediaTypes.FirstOrDefault(h => h.MediaType == "application/json");
if (jsonMediaType != null)
{
return new MediaTypeFormatterMatch(formatter, jsonMediaType, 1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral);
}
}
return defaultMatch;
}
}
And replace in HttpConfiguration object
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator());
I'm trying to pass data via post method from my client to a server.
I'm using WebApi to do so.
This i the code i used:
client:
var client = new RestClient();
client.EndPoint = #"http://localhost:57363/hello";
client.Method = HttpVerb.POST;
client.PostData = "{value: Hello}";
var json = client.MakeRequest();
Console.WriteLine(json);
Console.Read();
server:
// POST api/<controller>
public string Post([FromBody]string value)
{
return value + ", world.";
}
The server responds as expected when using postman. However, the client passes a null value instead of the real value.
What am i doing wrong?
First of all a correct json would look like "{value: 'Hello'}".
I use json-online to easily validate such inline json.
On the other hand, I think that you should send just the value in this case, not the entire json (because you are trying to resolve a simple type,a string), so the client should send a request like:
client.PostData = "'Hello'";
how can i directly call my own server side function using XMLHttpRequest.
suppose i have one static webmethod in my aspx file then how can i call it by XMLHttpRequest. what header info i need to pass to asp.net engine and as a result asp.net engine can invoke my method and return the response back in the out going stream.
this way i need to call my server side method
<script type="text/javascript">
var request;
// A
// Here is the new function that is called when the user submits the form.
// This example uses POST.
function submitCallback() {
var inputValue = document.getElementById("SearchInput").value;
var sendStr = "name=" + inputValue;
request = new XMLHttpRequest();
// B
// Specify the POST method and send it.
request.open("POST", "Default.aspx/Getdata");
request.onreadystatechange = readyCallback;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("IsLookup", "true");
request.send(sendStr);
}
</script>
please guide me....thanks
I believe you are probably referring to ASP.NET Page Methods when you say One static webmethod in my aspx file. ASP.NET page methods (or web services for consumption in JS) uses JSON serialization for i/p and o/p. So you need to set JSON as the content type for the request and actually send the JSON string in the body i.e.
...
var sendStr = "{name:" + inputValue + "}";
...
request.setRequestHeader("Content-Type", "application/json");
...
request.send(sendStr);
Further, I will suggest you to use jquery or ASP.NET generated proxies (by ScriptManager) instead of directly coding against XmlHttpRequest. See this article for how to use jquery for calling Page methods.
I think, the easiest way will be usage of jQuery for ajax requests: http://api.jquery.com/category/ajax/
If the controller action has the OutputCache attribute specified on an action, is there any way to clear the output cache without having to restart IIS?
[OutputCache (Duration=3600,VaryByParam="param1;param2")]
public string AjaxHtmlOutputMethod(string param1, string param2)
{
var someModel = SomeModel.Find( param1, param2 );
//set up ViewData
...
return RenderToString( "ViewName", someModel );
}
I'm looking at using HttpResponse.RemoveOutputCacheItem(string path) to clear it, but I'm having trouble figuring out what the path should be to map it to the action method. I'm going to try again with the aspx page that is rendered by ViewName.
Possibly I'll just manually insert the output of RenderToString into the HttpContext.Cache instead if I can't figure this one out.
Update
Please note that the OutputCache is VaryByParam, and testing out a hardcoded path "/controller/action" does not actually clear the outputcache, so it looks like it has to match "/controller/action/param1/param2".
That means I'll probably have to revert to object level caching and manually cache the output for RenderToString() :(
Try this
var urlToRemove = Url.Action("AjaxHtmlOutputMethod", "Controller");
HttpResponse.RemoveOutputCacheItem(urlToRemove);
UPDATED:
var requestContext = new System.Web.Routing.RequestContext(
new HttpContextWrapper(System.Web.HttpContext.Current),
new System.Web.Routing.RouteData());
var Url = new System.Web.Mvc.UrlHelper(requestContext);
UPDATED:
Try this:
[OutputCache(Location= System.Web.UI.OutputCacheLocation.Server, Duration=3600,VaryByParam="param1;param2")]
Otherwise the cache deletion won't work because you've
cached the HTML output on the user's machine
Further to the accepted answer, to support VaryByParam parameters:
[OutputCache (Duration=3600, VaryByParam="param1;param2", Location = OutputCacheLocation.Server)]
public string AjaxHtmlOutputMethod(string param1, string param2)
{
object routeValues = new { param1 = param1, param2 = param2 };
string url = Url.Action("AjaxHtmlOutputMethod", "Controller", routeValues);
Response.RemoveOutputCacheItem(url);
}
However Egor's answer is much better, because it supports all OutputCacheLocation values:
[OutputCache (Duration=3600, VaryByParam="param1;param2")]
public string AjaxHtmlOutputMethod(string param1, string param2)
{
if (error)
{
Response.Cache.SetNoStore();
Response.Cache.SetNoServerCaching();
}
}
When SetNoStore() and SetNoServerCaching() are called, they prevent the current Request being cached. Further requests will be cached, unless the functions are called for those requests as well.
This is ideal for handling error situations - when normally you want to cache responses, but not if they contain error messages.
I think correct flow is:
filterContext.HttpContext.Response.Cache.SetNoStore()
Add code to AjaxHtmlOutputMethod
HttpContext.Cache.Insert("Page", 1);
Response.AddCacheItemDependency("Page");
To clear output cache you can now use
HttpContext.Cache.Remove("Page");
Another option is to use VaryByCustom for the OutputCache and handle the invalidation of certain cache elements there.
Maybe it works for you, but it's not a general solution to your problem