I am using RedirectToRoute in my API controller to redirect to MVC controller. I was unable to find a good solution other than this:
return RedirectToRoute("Cv", new { action = "Cv/OpenCv" });
Previously I tried this below, but it didn't work.
return RedirectToRoute("Cv", new { controller="Cv", action = "OpenCv" });
Api and MVC Controllers use different Routes. RedirectToRoute in Api controller returns "System.Web.Http.Results.RedirectToRouteResult" but RedirectToRoute in Mvc Controller returns "System.Web.Mvc.RedirectToRouteResult". I think you can use just "Redirect" method in this case.
You can try to create an Mvc UrlHelper instance and use a RouteUrl method to build an Url from route parameters and then call Redirect method.
You can redirect from API controller to MVC controller by the help of below code.
Please find below code for the above question.
public IHttpActionResult Index()
{
var newUrl = this.Url.Link("Default", new
{
Controller = "Account",
Action = "Register"
});
return Redirect(new Uri(newUrl.ToString(), UriKind.RelativeOrAbsolute));
}
or follow the direct call from API Controller
public IHttpActionResult Index()
{
return Redirect(new Uri("/Account/Register", UriKind.RelativeOrAbsolute));
}
Please use the above code and let me know
Related
There was this sample code which had the following routing param defined as
[HttpPost]
[Route("save-file-to-physicallocation")]
public async Task<IActionResult> SaveToPhysicalLocation([FromBody] SaveFile saveFile)
{
foreach (var file in saveFile.Files)
{
string fileExtenstion = file.FileType.ToLower().Contains("png") ? "png" : "jpg";
string fileName = $#"D:\MyTest\{Guid.NewGuid()}.{fileExtenstion}";
using (var fileStream = System.IO.File.Create(fileName))
{
await fileStream.WriteAsync(file.ImageBytes);
}
}
return Ok();
}
What does this mean?
I know routing param with respect to controller.
[ApiController]
[Route("api/firewall")]
which means http://someurl/api/firewall
what does this mean?
[Route("save-file-to-physicallocation")]
In ASP.NET MVC Controller you can specify routing using Route() attribute. It accepts a string that specify the part of URL used to access that Controller or action.
In case you have Route() specified on Controller then actions accessed using that route and action method. Sometimes, you might need different route for specific action in addition to Controller route. Cases like having two actions with GET method then you need to add another segment to one of those actions to identify it from the other.
Let's take the following routing on your Controller class:
[ApiController]
[Route("api/firewall")]
This route on action method in that class:
[Route("save-file-to-physicallocation")]
Then to access that route you should send request to api/firewall/save-file-to-physicallocation to hit that action.
BTW you can do the same by adding to action route to the HTTP method attribute:
[HttpPost("save-file-to-physicallocation")]
That will basically provide the same functionality but with less used attributes.
I am working on Asp.Net MVC application where I don't want to display define action name in url. So I am applying ActionName with Action in controllers. But when I am defining ActionName with Action then it's not working and showing error page of 404 - not found. So please can you guide me to resolve this issue ?
public ActionResult Login()
{
//code
}
when I am passing url like domain/Login then it's working properly.
[ActionName("SignIn")]
public ActionResult Login()
{
//Code
}
but when I am applying ActionName like above then it's showing error page of 404.
I check about this issue on google but not any work for me.
While returning from the controller , for the same controller you have to specify like
return View("Login");
If you are redirecting to another controller action
return RedirectToAction("ActionName", "ControllerName");
and if you are using javascript to navigate for this action,use like
window.location.href="/ControllerName/SignIn";
Try
[ActionName("SignIn")]
public ActionResult Login()
{
//Code
return View("Login");
}
My problem is that I've added a new route [HttpGet("public-profile/{avatarName}")] in PublicProfile action and I don't know how to redirect to this Action.
So this is the Action that I want get redirected
[HttpGet("public-profile/{avatarName}")]
public async Task<ActionResult> PublicProfile(string avatarName)
{
return View();
}
What I had try was this way
[HttpPost]
public ActionResult PublicProfle()
{
return RedirectToAction("PublicProfile", "name");
}
However it isn't working
I've read about it here but it doesn't help me
RedirectToAction As Get Request format
RedirectToAction with parameter
ASP.Net Core MVC RedirectToAction is appending controller name in front of returnUrl
Try
return RedirectToAction("PublicProfile", new { avatarName = "name" });
I'm surprised I haven't come across this before, but I'm attempting to find a way to redirect to the default route post-authentication based on a user's role.
To set up an example, let's say there are two roles, Admin and Tester. An Admin's default route should be admin/index and the AdminController shouldn't be accessible to a Tester. A Tester's default route should be test/index and the TestController shouldn't be accessible to Admin.
I looked into route constraints, but apparently they can only be used to determine whether a route is valid. Then I attempted to try to call RedirectToAction after logging in, but that got a bit messy with return URLs and another reason that made it even more of a no-no which I can't remember at the moment.
I've landed on the following which I've implemented in my BaseController, but it's less than optimal to execute this on every controller action:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Controller.GetType() == typeof(TestController) &&
User.IsInRole("Admin"))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Admin", action = "Index" }));
else if (filterContext.Controller.GetType() == typeof(AdminController) &&
User.IsInRole("Tester"))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Test", action = "Index" }));
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
}
}
Is there a best practice for handling the default route based on user role?
using Microsoft.AspNet.Identity;
[Authrorize]
public class AdminController : Controller{
/* do your stuff in here. If your View is not actually a big difference from the tester view and you will only Hide some objects from the tester or viceversa, I suggest you use the same View but make a different methods inside the Controller. Actually you don't need to make AdminController and Tester Controller at all. */
}
// you can just do this in one Controller like
[Authorize(Roles="Admin")]
public ActionResult DetailsForAdmin(int id)
{
var myRole = db.MyModelsAccounts.Find(id);
return View("Admin", myRole); //<- Admin returning View
}
[Authorize(Roles="Test")]
public ActionResult DetailsForTester
I think you get the Idea.
As a result of a previous question of mine, I have discovered two ways of handling REST routes in MVC3.
This is a followup question where I am trying to learn factual differences/subtleties between these two approaches. I am looking authoritative answer if possible.
Method 1: Single Route, with Action Name + Http Verb Attributes on Controller Actions
Register a single route in Global.asax using a specified action parameter.
public override void RegisterArea(AreaRegistrationContext context)
{
// actions should handle: GET, POST, PUT, DELETE
context.MapRoute("Api-SinglePost", "api/posts/{id}",
new { controller = "Posts", action = "SinglePost" });
}
Apply both ActionName and HttpVerb attributes to controller actions
[HttpGet]
[ActionName("SinglePost")]
public JsonResult Get(string id)
{
return Json(_service.Get(id));
}
[HttpDelete]
[ActionName("SinglePost")]
public JsonResult Delete(string id)
{
return Json(_service.Delete(id));
}
[HttpPost]
[ActionName("SinglePost")]
public JsonResult Create(Post post)
{
return Json(_service.Save(post));
}
[HttpPut]
[ActionName("SinglePost")]
public JsonResult Update(Post post)
{
return Json(_service.Update(post););
}
Method 2: Unique Routes + Verb Constraints, with Http Verb Attribute on Controller Actions
Register unique routes in Global.asax with HttpMethodContraint
var postsUrl = "api/posts";
routes.MapRoute("posts-get", postsUrl + "/{id}",
new { controller = "Posts", action = "Get",
new { httpMethod = new HttpMethodConstraint("GET") });
routes.MapRoute("posts-create", postsUrl,
new { controller = "Posts", action = "Create",
new { httpMethod = new HttpMethodConstraint("POST") });
routes.MapRoute("posts-update", postsUrl,
new { controller = "Posts", action = "Update",
new { httpMethod = new HttpMethodConstraint("PUT") });
routes.MapRoute("posts-delete", postsUrl + "/{id}",
new { controller = "Posts", action = "Delete",
new { httpMethod = new HttpMethodConstraint("DELETE") });
Use only an Http Verb Attribute on the Controller Actions
[HttpGet]
public JsonResult Get(string id)
{
return Json(_service.Get(id));
}
[HttpDelete]
public JsonResult Delete(string id)
{
return Json(_service.Delete(id));
}
[HttpPost]
public JsonResult Create(Post post)
{
return Json(_service.Save(post));
}
[HttpPut]
public JsonResult Update(Post post)
{
return Json(_service.Update(post););
}
Both of these methods let me have uniquely named Controller Action Methods, and allow for RESTful routes tied to the verbs... but what is inherently different about restricting the route vs. using a proxy action name?
You won't get an authoritative answer by here are my 2 cents:
I prefer method 2 because then you have all your routing in one place. You can encapsulate your routing into a method e.g. MapResourceRoutes(string controller, string uri) and have it used muptiple times throughout your API.
Also method 2 gives you clearly named routes that you can use for linking and reverse routing.
I don't know that you will ever find an authoritative answer, but I will offer my opinion and as you can tell by my points, my opinion matters ;-). My purist self thinks that the first option is more pure, however my experience has been that helper methods like Url.Action() can sometimes have trouble resolving the correct route with this approach and I have taken to the second method as it really only has implications internally as the api looks identical to the consumer.
At this point, the correct answer is use Web API.