Redirecting in ASP.NET MVC with parameters - asp.net-mvc

I have the following code but it doesn't seem to redirect to my action with the given parameter. I have redirected something similar but the parameters were query string parameters. I'm wondering if it is done another way for parameters since the following doesn't work or what I might be doing wrong in my call to the action?
public ActionResult PassThrough (long i)
{
return RedirectToAction("RedirectAction", new { d = i});
}
public ActionResult RedirectAction (long d)
{
return SomeView();
}

You need to return the redirection command as result:
public ActionResult PassThrough (long i)
{
return RedirectToAction("RedirectAction", new { d = i});
}

Related

Cannot get a response from a Web API call

I have the following in the TreeController controller in a small web API:
[HttpGet("GetDirectories")]
public IActionResult GetDirectories()
{
var baseDir = _config["QuickShare:BaseDir"];
if (string.IsNullOrWhiteSpace(baseDir))
{
throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
}
var ret = GetDirectories(baseDir); ;
return Json(ret);
}
private List<DirectoryInfo> GetDirectories(string parentDir)
{
var dirInfo = new DirectoryInfo(parentDir);
return dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly).ToList();
}
When I try and call this action from Postman, I get told
Could not get any response There was an error connecting to
http://localhost:59243/api/Tree/GetDirectories.
Now the default, test, controller that comes with the project template is unchanged:
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] {"value1", "value2"};
}
...
}
And when I have the API running in Visual Studio, I can get a proper response from the Values controller, but not from the TreeController, yet they are almost exactly the same. And, when I call the Tree/GetDirectories` action, a breakpoint in that action method is hit, and I can single step through the very few lines that my method has, and they all execute fine.
The problem only becomes apparent when that last line of the action executes:
return Json(ret);
Then I get shown that Postman Could not get any response despite no exception being raised; while debugging the code, it looks like everything should work fine, and the requests to the Values controller work fine.
Your action method should return either the specific result type (JsonResult when you return Json ) or IActionResult.
Example:
[HttpGet("GetDirectories")]
public JsonResult GetDirectories()
{
var baseDir = _config["QuickShare:BaseDir"];
if (string.IsNullOrWhiteSpace(baseDir))
{
throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
}
var ret = GetDirectories(baseDir);
return Json(ret);
}
OR
[HttpGet("GetDirectories")]
public IActionResult GetDirectories()
{
var baseDir = _config["QuickShare:BaseDir"];
if (string.IsNullOrWhiteSpace(baseDir))
{
throw new InvalidOperationException("'QuickShare:BaseDir' is not configured");
}
var ret = GetDirectories(baseDir) ;
return Ok(ret);
}
You can get more help from Microsoft Documentation: Formatting Response Data

How to map querystring to action method parameters in MVC?

I have a url http://localhost/Home/DomSomething?t=123&s=TX and i want to route this URL to the following action method
public class HomeController
{
public ActionResult DoSomething(int taxYear,string state)
{
// do something here
}
}
since the query string names does not match with action method's parameter name, request is not routing to the action method.
If i change the url (just for testing) to http://localhost/Home/DomSomething?taxYear=123&state=TX then its working. (But i dont have access to change the request.)
I know there is Route attribute i can apply on the action method and that can map t to taxYear and s to state.
However i am not finding the correct syntax of Route attribute for this mapping, Can someone please help?
Option 1
If Query String parameters are always t and s, then you can use Prefix. Note that it won't accept taxYear and state anymore.
http://localhost:10096/home/DoSomething?t=123&s=TX
public ActionResult DoSomething([Bind(Prefix = "t")] int taxYear,
[Bind(Prefix = "s")] string state)
{
// do something here
}
Option 2
If you want to accept both URLs, then declare all parameters, and manually check which parameter has value -
http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX
public ActionResult DoSomething(
int? t = null, int? taxYear = null, string s = "", string state = "")
{
// do something here
}
Option 3
If you don't mind using third party package, you can use ActionParameterAlias. It accepts both URLs.
http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX
[ParameterAlias("taxYear", "t")]
[ParameterAlias("state", "s")]
public ActionResult DoSomething(int taxYear, string state)
{
// do something here
}

How might I simultaneously bind FromQuery and FromRoute parameter?

I am needing to simultaneously support a query-parameter based route (/api/models?id=1) and a route based one (/api/models/1) while still allowing unambiguous access to the models collection (/api/models)?
My controller looks (something) like this:
[Route("/api/{controller}")]
public class ModelsController : Controller
{
[HttpGet]
public Models[] GetModels([FromQuery]QueryOptions queryOptions)
{
//...
}
[HttpGet("{id:int}")]
public Model Get([FromRoute] int id)
{
//...
}
[HttpGet("?{id:int}")]
public Model Get2Try1([FromQuery] int id)
{
//Fails with ": The literal section '?' is invalid.
//Literal sections cannot contain the '?' character."
//Which makes sense after some reading...
}
[HttpGet]
public Model Get2Try2([FromQuery] int id)
{
//Fails with "AmbiguousActionException: Multiple actions matched.
//The following actions matched route data and had all constraints satisfied:
//GetModels and Get2Try2"
//Which I think I understand as well...the absence of optional params
//means ambiguous routing...
}
[HttpGet] //What here?
public Model Get2Try3([FromQuery] int id) //and/or here?
{
}
}
I feel like there should be some way to (with declarative routing) accomplish this. Has anyone done anything along these lines?
Also, current code base is ASP.NET Core (RC1) to be upgraded to RTM/1.0 shortly. Details on either side are likely similar, but am interested in either/both.
I've found that the following works:
[HttpGet, Route("{id?}")]
... the key being mainly the '?'. You don't need any [FromX] in the method signature, this does the trick and caters for both query string and route parameter passing.
Unfortunately Swagger UI doesn't like it and expects some explicit parameter to work out of the box (https://github.com/domaindrivendev/Ahoy/issues/47 or https://github.com/domaindrivendev/Ahoy/issues/182), but that's another story :)
I had the same problem.
There aren't solutions that works (against wep api .net) with web api core.
If we set [Route("{id}")] and [Route("")] doesn't work; if we set only [Route("{id?}")] the query parameter is empty if I use querystring.
So, I've used a workround.
I used [Route("{id?}")], but inside the function I get param from Request.Query
Example
public T Cast<T>(string input)
{
T output = default(T);
if (string.IsNullOrWhiteSpace(input))
return output;
input = input.Trim();
try
{
Type typeToCastTo = typeof(T);
if (typeof(T).IsGenericType)
typeToCastTo = typeToCastTo.GenericTypeArguments[0];
if (typeToCastTo.IsEnum)
{
if (Enum.IsDefined(typeToCastTo, input))
return (T)Enum.Parse(typeToCastTo, input);
return output;
}
object value = Convert.ChangeType(input, typeToCastTo, CultureInfo.InvariantCulture);
return (value == null) ? output : (T)value;
}
catch
{
return output;
}
}
public void MapQuerystringParams<T>(ref T param, string name)
{
var q = Request.Query[name].FirstOrDefault();
if (q != null)
{
var cast = Cast<T>(q);
if (!cast.Equals(default(T)))
param = cast;
}
}
[Route("api/[controller]/[action]")]
[ApiController]
public class ActivityController : ControllerBase
{
//examples of call
//https://localhost:44345/api/Activity/GetActivityByCode/7000
//https://localhost:44345/api/Activity/GetActivityByCode/?Id=7000
[HttpGet]
[Route("{Id?}")]
public IActionResult GetActivityByCode(int Id)
{
MapQuerystringParams(ref Id, "Id"); //this take param from querystring if exists
ActivityBusiness business = new ActivityBusiness(new BusinessInitializer { config = configuration });
ActivityDTOModel activity = business.GetActivityByCode(Id);
return Ok(activity);
}
}
Ideally in the domain design if you can have one method serving one specific function then great. Recently I had to faithfully implement a legacy API and it wasn't an option for me to decompose the design of my API.
If you are suffering from ambiguous routes in MVC6 and need to differentiate unique Routes given specific QueryStrings that have been supplied at one single POST method. Then IActionConstraint can help! Here is some example code of me using it :
using System;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
namespace Automation.Api.Service.Attributes
{
public class RoutingSpecificAttribute : Attribute, IActionConstraint
{
private string _keyParam;
public RoutingSpecificAttribute(string routingParameter)
{
this._keyParam = routingParameter;
}
public int Order
{
get
{
return 0;
}
}
public bool Accept(ActionConstraintContext context)
{
if (this._keyParam == null) { return true; }
switch (this._keyParam)
{
case "name": return context.RouteContext.HttpContext.Request.Query.ContainsKey(this._keyParam);
case "noquerystring": return context.RouteContext.HttpContext.Request.Query.Count == 0;
default:
return false;
}
}
}
}
This one method in the API that I needed to author both serviced a separate create + update functions based on the existence of a couple of QueryStrings: name & version.
So to help disambiguate you can distinctly decorate each of the methods within your controllers within said controller class [RoutingSpecific("noquerystring")] or [RoutingSpecific("name")] to help differentiate.
MSDN class description
Example implementation - see Entropy github
For anyone that happens to stumble upon this as I have,
Using .Net Core 3.1 the following works:
Web Controller Method
[HttpGet("something/{id}")]
public IActionResult Get([FromRoute] id, [FromQuery] OptionalParams optionalParams)
{
// do stuff
}
Query Parameter Container
public class OptionalParams
{
[FromQuery(Name = "colour_of_thing")]
public string Colour { get; set; }
[FromQuery(Name = "shape_of_thing")]
public string Shape { get; set; }
[FromQuery(Name = "some_other_filter")]
public string SomeOtherFilter { get; set; }
}
Url
var id = Guid.NewGuid();
var colour = "red";
var shape = "circle";
var url = $"Http://localhost:5000/something/{id}?colour_of_thing={colour}&shape_of_thing={shape}";

In ASP.Net Web API, how do I map multiple http query parameters to a single method parameter

We're using ASP.Net Web API to generate a feed and it includes the ability to do paging.
myfeed.com/afeed?page=2
My boss says "let's also allow users to use 'paged', because that's what WP uses." In addition, we're also using pageIndex in some of our older feeds. So what I'd like to do is accept all three.
myfeed.com/afeed?page=2
myfeed.com/afeed?paged=2
myfeed.com/afeed?pageIndex=2
I'd like to do is be able to write a clean Web API method, such as
public Foo Get(int page = 1)
{
//do some stuff
return foo;
}
without cluttering the method with page 'plumbing'. So I tried creating an ActionFilter
public override void OnActionExecuting(HttpActionContext actionContext)
{
object pageParam = new object(); //query["page"]
if (pageParam == null)
{
var altPageParam = GetPageParamUsingAlternateParams(actionContext);
if (altPageParam != null){}
//SetPageParam here
}
base.OnActionExecuting(actionContext);
}
private object GetPageParamUsingAlternateParams(HttpActionContext actionContext)
{
object result = new object();
object pageIndexParam = new object(); //Query["pageIndex"]
object pagedParam = new object(); ////Query["paged"]
if (pagedParam != null)
result = pagedParam;
else if (pageIndexParam != null)
result = pageIndexParam;
return result;
}
I didn't finish. As I was looking for the best way to get the query params, I stumbled into a big mistake!
OnActionExecuting is executed after int page = 1. Sure, I could override it in an ActionFilter, but that would lead to confusion down the road. I really want to be able to do a simple flow through the URI query parameters that goes from
page -> paged -> pageIndex -> default value in method
I have found a lot of articles on custom binding to a an object. Also, I found articles about "parameter binding", however those dealt with FromUri and FromBody. I didn't find anything that I felt had a direct parallel to what I'm facing.
You could achieve what you want by defining 3 different GET method with parameters matched with the query segment of the Url like the code snippet below:
public class ProductsController : ApiController
{
//Matched api/products?page=1
public IHttpActionResult Get(int page)
{
return GetPagedData(page);
}
//Matched api/products?paged=1
public IHttpActionResult GetPaged(int paged)
{
return GetPagedData(paged);
}
//Matched api/products?pagIndex=1
public IHttpActionResult GetPageIndex(int pageIndex)
{
return GetPagedData(pageIndex);
}
//Do the real paging here
private IHttpActionResult GetPagedData(int page =1)
{
return Ok("Data Pages");
}
}

asp.net mvc - return view doesn't fire the code... url wrong

I have following code that is accepting a form submission
[ActionName("TestingTemp"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestingTemp(FormCollection result)
{
string cat = "";
return View("Try");
}
Now the problem is even though it seems to load "Try" page, things break on the page because it doesn't fire the following code (which does get properly fired if I directly go to Try page).
public ActionResult Try()
{
ViewData["Test"] = DataLayer.Test(0, 10);
return View();
}
Also the url contains TestingTemp where it should contain Try, if you know what I mean.
I think what you are looking for is RedirectToAction. It will redirect to your other method and rewrite the URL.
[ActionName("TestingTemp"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestingTemp(FormCollection result)
{
string cat = "";
return RedirectToAction("Try");
}
the preferred way is to use redirectToAction but if u do want to go that way then u have to put the required data that u r doing in Try method like
[ActionName("TestingTemp"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestingTemp(FormCollection result)
{
string cat = "";
ViewData["Test"] = DataLayer.Test(0, 10);
return View("Try");
}
but as i said this way is not preferred i.e repeating ur code in each action rather u can just write something like
[ActionName("TestingTemp"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestingTemp(FormCollection result)
{
string cat = "";
return RedirectToAction("Try");
}

Resources