I have a WebMethod which accepts one parameter.
When I send a request to the webmethod without any parameters everything works well but when I supply a parameter to the same method, it returns entire site instead of a string.
The page parameter changes nothing except the content of the list.
List is just ListView which displays list of strings.
When I use URLRewriting the URL is different in instances that I supply a parameter from instances when I do not.
Can anybody help me with this problem?
My WebMethod:
[WebMethod]
public static string GetResult(int id)
{
return "Hooray";
}
My web method call:
PageMethods.GetResult(docId,
function onSuccess(list) {
$(element).parent().siblings().filter(":first").append(list);
});
URL without parameter:
www.mywebsite.com/items is rewritten to www.mywebsite.com/items.aspx
URL with parameter:
www.mywebsite.com/items/1 is rewritten to www.mywebsite.com/items.aspx?id=1
Here's a discussion about your same issue that might shed some light on the situation. Basically, what it says is that it's not working because the handler that deals with PageMethods is looking for {pagename.aspx}/{methodname}, and your url rewriting is causing it to not recognize you are calling a page method.
One suggestion on that page was to add the following in your javascript code somewhere after the auto-generated call of the same signature:
PageMethods.set_path('/items.aspx');
This will make it call your page method using the real url instead of the rewritten one.
Related
I want know which page and which URL has calling my Handler .ashx, is that possible?
I need this because, I have an Handler who calls and convert images from database, but some of my URLS of images are not passing the right query argument (they don't exist in database) and I need what is the URL who call to see what is the image for that arguments.
why not just use
context.Request.UrlReferrer?
A quick solution to your immediate question is to call (in C#)
Inside your public void ProcessRequest(HttpContext context){} method, add the following 3 lines.
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
String referer = worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderReferer);
This will give you the URL of the page that called your handler.
To go further though, you should ideally be implementing error handling to handle any missing images.
I'm converting a legacy webforms app to MVC, working through it a page at a time. To make the project easier to work with I've moved all the webforms pages, which were previously in the route of the project into a /webforms subdirectory. So I need to capture any incoming requests for /page.aspx?param=123 and redirect them to /webforms/page.aspx?param=123. I thought an easy way to do this would be to setup a route handler that passed any such requests to a controller that does that job. I set up a route like so:
routes.MapRoute("WebformsRedirect", "{*page}",
new { controller = "Webforms", action = "ForwardToPage" },
new { page = #"\S+.aspx\S*" }
);
This kind of works but it doesn't capture the query string, only the page part. I can get the query string for the Request object in the controller so it's not a huge deal but it would be nice to be able to do it through the route only. My routing unit tests (which I copied from Steve Sanderson's MVC book) actually pass correctly when I test them with querystrings so I'm confused why it isn't working. Is my regular expression wrong? They aren't my strong point.
QueryStrings are not part of the routing
if you requested for example "Home/Index?foo=bar" and you have a route that match "Foo/Bar" to Controller Foo , Action Bar without any more routing info (don't know anything about foo) you still can write
class HomeController: Controller {
ActionResult Index(string foo) {
}
}
now foo variable will equal bar , why ?
because its the model binder that gets the value of the parameters passed.
the model binder check 4 repositories by default QueryString , Routing Place Holders ,FormsCollections and Files
so what i am trying to say , the route and QueryStrings are two different things , it doesn't need to capture it
I have a web service (an ASP.NET .asmx page), and for debugging purposes I need to log all calls to the webservice, including values of all parameters passed into each call. So basically the first thing each WebMethod should do is log it's state with details of all the parameter values passed in to it.
So far so good. The complication is that I also want an automated way of getting the parameter values - there's quite a few webmethods with different signatures, and some of them have up to ~30 parameters, so manually coding against each specific parameter would likely be massively error-prone. I'd rather be able to call a method that looks at the current Http context and automatically uses that to grab and parse whatever has been passed in by the client.
But I hit a snag. When I look at HttpContext.Current.Request, it turns out that both the Form and QueryString collections are empty. So if the arguments passed to the webmethod aren't in either of those collections, where would they be? Anyone know how I can retrieve them?
You can use AOP techniques for this task. Considering PostSharp, you can create custom aspect like this:
[Serializable]
public class TraceAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Trace.WriteLine(string.Format("Entering {0}", args.Method.Name));
for (int i = 0; i < args.Arguments.Count; i++)
{
Trace.WriteLine(string.Format(" {0}", args.Arguments.GetArgument(i)));
}
}
}
and then apply it to your web-service methods:
[WebMethod, Trace]
public string HelloWorld()
{
return "Hello World";
}
You could use SOAP extensions and follow the example in this post to log the request which would have the method name and parameters.
SOAP Extentions is a better choice. Here is another example to retreive SOAP request and SOAP response as XML. All you do is parse the XML to retreive parameter name value pairs.
i wish to have a simple Action in my controller that accepts a few optional values and some integer values.
this is my route i wish to have:
HTTP.POST
/review/create
and this is the Action method i would like...
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Create(int userId,
int addressId,
byte baseScore,
byte reviewType,
string subject,
string description)
{ ... }
I'm under the uneducated impression that all of those arguments above will be populated by the forms collection values ... but it's not happening. Also, I have no idea how I would write a route, to handle those ... because those values are form post data....
here's my global.asax....
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Api - Search methods.
routes.MapRoute(
"Search Methods",
"{controller}/{action}"
);
In fact, the action method is never called because it doesn't seem to find it :(
But, if create and action without any of those arguments, then it finds it ?????????
How would you write a route and action method to accept some require and some optional arguments, for the route /review/create ?
As far as i can see you may rewrite your controller action like this:
public ActionResult Create(int foo, int bar, byte blah, string name, int? xxx) {
// code here
}
The ModelBinder will then ensure that foo,bar and blah are set. Name and xxx may be null. I can't test it a the moment, but i think return type of the action should be ActionResult.
If you are POST'ing a form, just make sure that the elements in your form (textboxes, checkboxes, textarea, etc) have id's that match the parameters in your method. As an alternative you can pass a FormCollection to the method, and do myFormCollection["foo"] to get a string representation of the value (which can then be parsed to an int).
From my experience, you are missing a number of key elements and concepts with this question.
First and foremost, I don't believe you can execute a POST without a form. The form has to contain the controls from which you pull the values that get passed to the controller method. If the goal is to simply unit test your POST controller method, then just call the method directly in your test, which it appears that you're doing, based on one of your comments. If you involve the view, then you're doing integration testing, not unit testing. Regardless of the test type, the test will always fail because you are choosing not to build the form. Even if you manage to force the POST using Fiddler, Firebug or any other mechanism, you're still not testing the view, you're testing the HTTP protocol.
I highly recommend that you employ a web application testing tool, such as WatiN or Selenium, to test your web pages, rather than throw together a quick-and-dirty test that really doesn't test anything useful.
In your post request set content-type="application/json; charset=UTF-8" and pass the values for the method parameter in JSON format. This should make Asp.MVC not to look in FormCollection for those values.
I'm having a problem getting a controller method that returns a JsonResult to accept parameters passed via the JQuery getJSON method.
The code I’m working on works fine when the second parameter ("data") of the getJSON method call is null. But when I attempt to pass in a value there, it seems as if the controller method never even gets called.
In this example case, I just want to use an integer. The getJSON call that works fine looks like this:
$.getJSON(”/News/ListNewsJson/”, null, ListNews_OnReturn);
The controller method is like this:
public JsonResult ListNewsJson(int? id)
{
…
return Json(toReturn);
}
By putting a breakpoint in the ListNewsJson method, I see that this method gets called when the data parameter of getJSON is null, but when I replace it with value, such as, say, 3:
$.getJSON(”/News/ListNewsJson/”, 3, ListNews_OnReturn);
… the controller method/breakpoint is never hit. Any idea what I'm doing wrong?
I should also mention that the controller method works fine if I manually go to the address via my browser ("/News/ListNewsJson/3").
getJSON expects a set of key/value pairs, not a bare value, so you would need to use { id: 3 } to pass an id value. Unfortunately this will get turned into /News/ListNewsJson/?id=3 which is not what you want. I suggest just appending the value onto the Url to construct it in the route form. I'm also assuming that the value actually comes from a variable so I've written it in that form. If it's possible to be null, then you'll need to do something more complicated to formulate the Url so it makes sense.
var id = '3';
$.getJSON(”/News/ListNewsJson/” + id, ListNews_OnReturn);
i know this is an older thread, but why aren't you using the MVC Url.Action() helper? This would make sure your route is correct.
$.getJSON('<%=Url.Action("ListNewsJson", "News") %>/' + id, ListNews_OnReturn);
Of course, if the id value comes from ViewData you could use the 3rd parameter of the Url.Action() helper method to pass in an anonymous type with an id property, and MVC will create the desired URL. Otherwise, concat it in javascript if the value is coming from the javascript function.
HTH