How to use Fiddler 2 to compose a request? - asp.net-web-api

I am using asp.net web api and I want to try to see if my method work. The way I see people do this alot is through fiddler. I am trying to do this myself but I can't get it to work.
I go to the composer tab and do this.
public IQueryable<FoodLogRecord> Get(string email)
{
return null;
}
but I get a 404 back. I also put a break point in the method and it never goes in.

Use the URL
http://localhost:50570/api/foodlog?email=c
Remove the Content-Length and the text from the request body. You can't send a body with a GET request.

You should be able to use the following URL with the code changes below: http://localhost:50570/api/foodlog/c
public IQueryable<FoodLogRecord> Get([FromUri] string email)
{
return null;
}

Related

"the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request."

I'm trying to implement ajax pagination using Umbraco.
On the server side, I have the following:
[System.Web.Http.HttpGet]
public JsonResult pagination(int? page)
{
IEnumerable<IPublishedContent> newsPosts = Umbraco.AssignedContentItem.DescendantOrSelf("news").Children.Where(x => x.IsVisible() && x.DocumentTypeAlias == "newsPost").OrderByDescending(x => x.UpdateDate).Take(5);
//from here on we will be returning the json within which information required for displaying post entries in carousel is included.
string json = "[some random string]"; //just random string for now.
return Json(json, JsonRequestBehavior.AllowGet);
}
As you can see, I'm trying to get necessary data from IPublishedContents, but I'm having trouble instantiating this series of IPublishedContents.
And this is the error I'm getting when I access:
locahost:{port}/umbraco/surface/{controller}/pagination on Chrome.
Cannot return the IPublishedContent because the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request.
Details: System.InvalidOperationException: Cannot return the IPublishedContent because the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request.
As I said, I'm making this request from Chrome, which is I think means this request is from the front end, so I'm not sure why I'm getting this error.
In the course of searching I found these
1) our.umbraco.com forum
2) stackoverflow post
is deserted with no answer, and as for 2, it strikes me that the answer is not quite relevant to my case. I want to instantiate IPublishedContent in the first place.
Mine is Umbraco 7.
and could it be possible to tell me why requests from the front-end are not desirable?
Any hint would be highly appreciated.
Thanks,
Try getting your node this way.
var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var yourNode = umbracoHelper.TypedContentAtXPath("umbracoPathtoYourNode");
Perhaps easier to use web api
Create a controller which inherits from UmbracoApiController
public class PagedItemsController : UmbracoApiController
{
[HttpGet]
[ActionName("list")] //Optional see note below
public IHttpActionResult GetItems([FromUri] int pageNo = 1)
{
// Next you need some way of getting the items you need.
// I would not return the whole IPublishedContent items. Rather query those and then use linq Select to transform into a more relevant smaller class (not doing this here)
// I've just included this for brevity
var items = _itemService.GetPagedItems(pageNo);
// Now return the results
return Ok(items);
}
}
Calls to endpoints in Umbraco follow the format
/umbraco/api/{controller}/{endpoint}
With the [ActionName("list")] above the call to the GetItems method will be
http://example.com/umbraco/api/PagedItems/list?pageNo=3
Without the ActionName attribute the call would be
http://exampe.com/umbraco/api/PagedItems/GetItems?pageNo=3
With a standard jquery ajax call this will return json without needing to serialise.

Redirect from void action

I have a void function that based on a conditional statement should redirect users to a different action.
public void MyFunction()
{
if (!condition)
{
Redirect(url);
}
...
...
}
Using redirect without a return statement doesn't seem to work. Is there a more suitable method for accomplishing this?
Response.Redirect("Some URL") or Server.Transfer("Some URL") can be used to redirect any web page
Response.Redirect("Some URL") should be used when to :
redirect the request to some plain HTML pages on our
server or to some other web server
not to care about causing additional roundtrips to the server on each request
not need to preserve Query String and Form Variables from the original request
to be able to see the new redirected URL where he is
redirected in his browser (and be able to bookmark it if its
necessary)
Server.Transfer("Some URL") should be used when to:
transfer current page request to another .aspx page on the
same server
preserve server resources and avoid the
unnecessary roundtrips to the server
preserve Query String and Form Variables (optionally) we don't need to show the real URL
where we redirected the request in the users Web Browser
try this
public IActionResult MyFunction()
{
if (!condition)
{
return Redirect(url);
}
...
...
}
About IActionResult
Actions can return anything, but frequently return an instance of
IActionResult (or Task for async methods) that produces
a response. The action method is responsible for choosing what kind of
response. The action result does the responding.
from https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/actions
You may get more information about action methods at above link

Spring MVC test post method with controller redirect

I have a test:
#Test
public void shouldAddCompany() throws Exception {
mockMvc.perform(post("/companies")
.param("name", "companyName"))
.andExpect(model().attribute("company",
hasProperty("name", is("companyName"))));
}
and my controller method looks like that:
#PostMapping("/companies")
public String displayCompaniesPost(#ModelAttribute Company company) {
companyService.save(company);
return "redirect:/companies";
}
How can i check company attribute in test? There is a problem because of redirect and status 302.
java.lang.AssertionError: Model attribute 'company'
Expected: hasProperty("name", is "companyName")
but: was null
I think it occurs because controller is going to GET method because of redirection. When I remove this redirection everything is ok, but I don't want to remove that redirection.
EDIT (GetMapping):
#GetMapping({"/", "/companies"})
public String displayCompanies(Model model) {
model.addAttribute("company", new Company());
List<Company> companies = companyService.findAll();
model.addAttribute("companies", companies);
return "companies";
}
I thought the problem is because of addding attribute with the same name in getMapping, but when I removed it, it still doesn't work.
You need to modify your approach. If you POST to a controller method, and it returns a Redirect you will have no ability to access any model information set by that controller, it just returns an HTTP 302 with a Location Header to the client telling it the new url to go to (in this case GET /companies). If this is a strictly Unit test, that is the extent of what you can test for this method.
I would consider instead treating this as an integration test, and change your test to have two separate steps:
POST /companies and validate that the response is the expected redirect
GET /companies and validate that the list of companies returned contains the new company you posted in step 1

Web API 2 attribute routing returning 404

I'm having trouble getting the Web API 2 attribute routing to work.
I've been trying everything I could find this whole evening but I can't find the problem.
What I want to achieve is the following:
Make a POST request to http://localhost:xxxx/api/chat/joingroup/1234 to get to the following API call:
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
This keeps getting me a http 400 message.
{"message":"No HTTP resource was found that matches the request URI 'http://localhost:41021/api/chat/joingroup/123'.",
"messageDetail":"No action was found on the controller 'Chat' that matches the request."}
But sending a post to: http://localhost:41021/api/chat/sendmessage/pm/123123 and also to http://localhost:41021/api/chat/joingroup gives me a 200
The chatcontroller:
[RoutePrefix("api/chat")]
public class ChatController : ApiController
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
[...]
[Route("joingroup/{id}")]
[HttpPost]
public async Task<IHttpActionResult> JoinGroup(string id, string connectionID)
{
await hubContext.Groups.Add(connectionID, id);
return Ok(hubContext.Groups.ToString());
}
HTTP POSTS to http://localhost:xxxx/api/chat/sendmessage are working fine.
I cannot figure out why it isn't going to the correct method when I'm calling a POST on http://localhost:xxxx/api/chat/joingroup/1234.
SOLUTION:
The solution was to reference both values that are needed in the JoinGroup method, id and connectionID. Now the request will hit this method.
Using:
http://localhost:xxxx/api/chat/joingroup/john?connectionid=123 will work.
I noticed two things on the code you sent through:
the path you POST to is: localhost:xxxx/joingroup/1234 , this
should be localhost:xxxx/api/chat/joingroup/1234
because you have 2 parameters for the joingroup, you will need to pass both of them through, may be like this localhost:xxxx/api/chat/joingroup/1234?connectionID=value or you can pass it on the request body
if the connectionID is optional you can modify the method to use option al parameters like this
public string JoinGroup(string id, string connectionID = "")
please let me know if this helps.
Thanks
Ashraf
I assume the connectionID parameter references the POSTed data. The easiest thing to make it work is to decorate it with the [FromBody] attribute and put an = in front of the value being sent like this: =MyConnection1.
Web API expects an object with properties or an array otherwise. Alternatively, you can wrap the connection ID with a custom class and pass it serialized as JSON/XML.

Spring redirect: prefix issue

I have an application which uses Spring 3. I have a view resolver which builds my views based on a String. So in my controllers I have methods like this one.
#RequestMapping(...)
public String method(){
//Some proccessing
return "tiles:tileName"
}
I need to return a RedirectView to solve the duplicate submission due to updating the page in the browser, so I have thought to use Spring redirect: prefix. The problem is that it only redirects when I user a URL alter the prefix (not with a name a resolver can understand). I wanted to do something like this:
#RequestMapping(...)
public String method(){
//Some proccessing
return "redirect:tiles:tileName"
}
Is there any way to use RedirectView with the String (the resolvable view name) I get from the every controller method?
Thanks
the call prefixed by redirect: is a url, which is sent in a standard browser 302 redirect. you can't redirect to a view, because a view isn't a url. instead you'll need a new servelet mapping to a 'success' view and then redirect to that instead
#RequestMapping("processing.htm")
public String method(){
//Some proccessing
return "redirect:success.htm"
}
#RequestMapping("success.htm")
public String method(){
return "tiles:tileName"
}
this case works fine when you just need to show a 'thank you' page, which requires no specific data from the processing stage. however, if your success page needs to show some information from the processing, there are 2 ways to do it.
1) pass the information in the url as a get post ("redirect:success.htm?message=hi"). this is incredibly hackable, and thus highly unrecommended.
2) the better way is to store information in the http session, using #SessionAttributes and #ModelAttribute

Resources