I'm trying to use RedirectToAction to redirect to one of the three actions below. However RedirectToAction is redirecting to /Move/Staging?userId=12345 which results in a 404. What I'm trying to do with the RedirectToAction is that it redirects to /Move/12345/Staging.
I'm using RedirectToAction as follows
return RedirectToAction("StagingMove", "Maintenance", new { userId = model.userId});
I've configured the Actions as followed.
[HttpGet("Move/{userId?}/Staging/")]
public async Task<IActionResult> StagingMove(string userId)
{
try
{
{Snip}
return View(user );
}
catch (Exception ex)
{
this._logger.LogError(0, ex, "Move User Staging");
throw ex;
}
}
[HttpGet("Move/{userId?}/Arrival/")]
public async Task<IActionResult> StagingArrival(string userId)
{
try
{
ApplicationUser user = await this._userManager.GetUserAsync(userId);
return View(user );
}
catch (Exception ex)
{
this._logger.LogError(0, ex, "Move User Arrival");
throw ex;
}
}
[HttpGet("Move/{userId?}/Departures/")]
public async Task<IActionResult> StagingDepartures(string userId)
{
try
{
ApplicationUser user = await this._userManager.GetUserAsync(userId);
return View(user );
}
catch (Exception ex)
{
this._logger.LogError(0, ex, "Move User Departures");
throw ex;
}
}
I've looked into this and as far as I can tell it does work for when you have Move/Staging/{userId}. However, I can't get it to work in my situation with stuff behind the parameter.
Thanks to #King-king I got it working.
attribute routing and convention-based routing are exclusively
effective. In this case you use attribute routing so the path used in RedirectToAction won't work.
I modified my actions, for example:
[Route("Move/{userId?}/Staging/", Name = "MoveStaging")]
public async Task<IActionResult> StagingMove(string userId)
{
try
{
{Snip}
return View(user );
}
catch (Exception ex)
{
this._logger.LogError(0, ex, "Move User Staging");
throw ex;
}
}
Now I can use RedirectToRoute.
return RedirectToRoute("MoveStaging", new { userId = model.userId});
Related
In my application there are certain "friendly" messages that the services layer returns to me through a custom exception "LimsDataException" and that I want to show in the corresponding view.
I solve them with a try/catch in the controller actions, generating a lot of repetitive code, could I solve it with an exception filter, with a custom middleware or in some other way?
[HttpPost]
public async Task<IActionResult> Create(PriorityVM vm)
{
if (ModelState.IsValid)
{
try
{
var priority = _mapper.Map<PriorityDto>(vm);
priority.Id = await _priorityService.Create(priority);
return RedirectToAction(nameof(Details), new { id = priority.Id });
}
catch (LimsDataException ex)
{
ModelState.AddModelError("", _dbLocalizer[ex.Message]);
}
}
return View(vm);
}
public class LimsDataExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is LimsDataException)
{
context.ModelState.AddModelError("", context.Exception.Message);
context.ExceptionHandled = true;
// Can I continue with the execution of the view? Do I need a Middleware?
}
}
}
screen
hello i write this code in asp.net core. for api request. so i will write return keyword in this code. what should i do to access a return keyword in below code?
[HttpPost]
[Route("UserDelete")]
public async Task UserDelete(string Id)
{
try
{
await _ICcontext.UserRegistrationDelete(Id);
}
catch(Exception Ex)
{
throw Ex;
}
}
Simply return with method OK() or Json() with the object you want to serialize.
[HttpPost]
[Route("UserDelete")]
public async Task<IActionResult> UserDelete(string Id)
{
try
{
return Ok(await _ICcontext.UserRegistrationDelete(Id));
}
catch(Exception Ex)
{
LogException(Ex);
return StatusCode(500);
}
}
I have .net core web api and able to access the get endpoint but not the delete. How do i access the delete endpoint. I am not sure what the problem is ?
I have tried the following
http://localhost:53538/api/cities/delete-city/1
I have been using for the get endpoint.
http://localhost:53538/api/cities
controller
public class CitiesController : Controller
{
private readonly ICityInfoService _cityInfoService;
public CitiesController(ICityInfoService cityInfoService)
{
_cityInfoService = cityInfoService;
}
[HttpGet]
public IActionResult GetCities()
{
var cities = _cityInfoService.GetCities();
if (!cities.Any())
return NoContent();
var citiesMapped = cities.Select(MapCity);
return Ok(citiesMapped);
}
[HttpGet("{cityId:int}")]
public IActionResult GetCity(int cityId)
{
try
{
var city = _cityInfoService.GetCity(cityId);
var cityMapped = MapCity(city);
return Ok(cityMapped);
}
catch (CityNotFoundException e)
{
return BadRequest(e.Message);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
[HttpDelete("delete-city/{cityId:int}")]
public IActionResult DeleteCity(int cityId)
{
try
{
_cityInfoService.DeleteCity(cityId);
return Ok();
}
catch (CityNotFoundException e)
{
return BadRequest(e.Message);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
private static CityDto MapCity(City city)
{
return new CityDto
{
Id = city.Id,
Description = city.Description,
Name = city.Name
};
}
}
Your delete method is a HttpDelete, so it needs DELETE request. If you a trying to hit the endpoint via a browser, it won't work as it will just do a GET.
You can use Curl or Postman to issue the DELETE request to your URL.
How can I implement exception handling in my view component?
Wrapping the logic from my action method into try/catch blocks doesn't catch any exceptions thrown within a view component itself, and I don't want the app to stop functioning regardless of any errors. This is what I'm doing so far and trying to accomplish:
Action Method
public IActionResult LoadComments(int id)
{
try
{
return ViewComponent("CardComments", new { id });
}
catch (SqlException e)
{
return RedirectToAction("Error", "Home");
}
}
To reiterate, this does not catch a SqlException that occurs inside the view component itself, and thus it fails to redirect.
View Component
public class CardCommentsViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int id)
{
try
{
IEnumerable<CardCommentData> comments = await DbHelper.GetCardCommentData(id);
return View(comments);
}
catch (SqlException e)
{
//Redirect from here if possible?
}
}
}
Can I accomplish this from the controller's action method? If not, how can I redirect from the view component itself? I've tried researching this problem and came up empty. Any information would be helpful.
You can try to redirect to another page using HttpContextAccessor.HttpContext.Response.Redirect:
public class CardCommentsViewComponent : ViewComponent
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CardCommentsViewComponent( IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync(int id)
{
try
{
IEnumerable<CardCommentData> comments = await DbHelper.GetCardCommentData(id);
return View(comments);
}
catch (SqlException e)
{
_httpContextAccessor.HttpContext.Response.Redirect("/About");
return View(new List<CardCommentData>());
}
}
}
Register in DI :
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
But the preferred way is using global exception handler /filter to trace the exception and redirect to related error page :
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2
I have an application with silvelight and wcf data services.
I want to populate comboBox with value of my column 'City'
Can someone give me the correct way to do this, because my function failed with System.InvalidOperationException !
public void GetCities(System.Windows.Controls.ComboBox cmbCity)
{
DataServiceQuery<String> userQuery = (DataServiceQuery<String>)proxy.CreateQuery<String>("GetCity");
try
{
userQuery.BeginExecute(
(result) =>
{
var userlist = new DataServiceCollection<string>(userQuery.EndExecute(result));
cmbCity.ItemsSource = userlist.ToList();
}, null);
}
catch (DataServiceQueryException ex)
{
throw ex;
}
}
In my WCF Data Service, :
[WebGet]
public IQueryable<String> GetCity()
{
return Usager.GetCity();
}
in my edmx project, I have this:
public static IQueryable<String> GetCity()
{
try
{
DataBaseEntities scv = new DataBaseEntities();
return (from user in scv.Usager
select user.City).Distinct();
}
catch (Exception ex)
{
throw ex;
}
}