Get RedirectToPage Generated URL ASP.NET Core - asp.net-core

You are able to redirect to other actions using built-in methods like:
RedirectToPage("./Index", new { StatusMessage = "Everything was processed successfully"" });
This will redirect to another PageModel that's in same directory and it's Index action. Is it possible to "extract" this functionality so that you get redirect location by just passing ./Index to some util function/method?

public class IndexModel : PageModel
{
public void OnGet()
{
string privacyPageUrl = Url.Page("./Privacy");
}
}

Related

Blazor WASM Http call is not hitting some API endpoints. Receiving index.html instead

I have a Blazor WASM page that need to make a call to get some data from an API. The Blazor app is ASPNetCore hosted, and the hosting app contains the API.
Some of my endpoints work, but some calls throw a Json serialization exception.
Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
If I look at the actual response from the server, it looks like it returns the content of index.html from my WASM app.
Example Controller
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private readonly ApplicationDbContext _context;
public CompanyController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(long id)
{
Company? company = await _context.Companies.FindAsync(id);
if (company == null)
{
return NotFound();
}
return Ok(company);
}
}
Example Blazor Page
#page "/companies/{id:long}"
#attribute [Authorize]
#inject HttpClient Http
#inject NavigationManager Nav
#if (company != null)
{
<div>#company.Name</div>
}
else
{
<div>Loading Company...</div>
}
#code {
private Company? company;
[Parameter]
public long Id { get; set; }
protected override async Task OnInitializedAsync()
{
try
{
company = await Http.GetFromJsonAsync<Company>($"/api/company/{Id}");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
}
}
In the example above, everything works as expected. But if I make the following two changes, I'll get the Json Exception mentioned above.
Create an identical controller named WorkOrderController. Everything else is identical including pulling the Company data from the database. Only the name of the controller is different.
Change the Http request to company = await Http.GetFromJsonAsync<Company>($"/api/workOrder/{Id}"); in the Blazor page.
Why would some endpoints work, and some wouldn't?
So, the requestUri passed to GetFromJsonAsync must be lowercase. My request was failing because I had a capital "O" in "workOrder".
I am not sure why this is a requirement of the request parameter, but alas, making the path lowercase fixed the issue.

Why does not working version in asp.net core controller

I want to use api version in my .net core project.Then search web and find that's solution.
Even though do exactly all solutions,but I can't get desired result.
So if any can help me,Please show me..
I add Microsoft.AspNetCore.Mvc.Versioning 4.0.0 Package in my project and ..
StartUp.cs
Then in my Controller Add Rout Attribute as Shown :
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
private readonly IBus _client;
private readonly string AppBaseUrl = MyHttpContext.AppBaseUrl;
//private readonly IGetUrl _globalUrl;
public SellerController(IBus client/*, IGetUrl globalUrl*/)
{
_client = client;
//_globalUrl = globalUrl;
}
[HttpGet("/Sellers/{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
...
}
}
With these code I expected that I can send request to 'Info' method by this url :
But that's not working and get 404 error code status.. when I delete "/v1.0" from url and send request, that's working. I will be glad to help me .. Thanks
In your code, we can find that you applied [HttpGet("/Sellers/{SellerId}")] with route
template begin with / to Info action method, which don't get combined with route templates applied to the controller. To make request to 'Info' method, you could use below URL.
https://localhost:5090/sellers/17
I expected that I can send request to 'Info' method by this url : https://localhost:5090/v1.0/sellers/17
To achieve your requirement, you can try to modify the code like below.
[HttpGet("/v{version:apiVersion}/Sellers/{SellerId}")]
public async Task<IActionResult> Info(long SellerId)
{
//...
//for testing purpose
return Ok(SellerId);
}
Test Result
Update:
If you'd like to include v{version:apiVersion} in route template of controller level attribute routing, you can try to apply [HttpGet("{SellerId}")] to Info action method and make request with https://localhost:5090/v1.0/seller/17.
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
[HttpGet("{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
//...

How to use an IPageFilter on razor page with no model

Is there a way to apply an IPageFilter on a razor page which does not have a model?
The page is a simple get request.
#page
#{
#functions{
public void OnGet()
{
}
}
}
Just want to know If it's possible to add a simple i.e. Authorize attribute (or any IPageFilter attributes) in the above page. As the attributes work on following page when there exist a child class of PageModel.
#{
#functions
{
[Authorize]
public class TestModel : PageModel
{
public void OnGet()
{
}
}
}
}
You could use a page application model convention to add one. There’s an AddFilter convention extension that accepts a func

Cannot post JSON to an ASP.NET Core RazorPage handler

I'm working with an ASP.NET Core RazorPage as an alternative to an MVC controller, and I want to be able to submit the client side form via XMLHttpRequest. I've already figured out the XSRF token bits so that passes the muster, but the RazorPages framework doesn't seem to process the inbound JSON payload and bind it to the property as expected.
Some code:
The page's model (.cshtml.cs):
public class IndexModel : PageModel
{
private Database database;
private ILogger logger;
[BindProperty]
public AddRequestModel MyRequest { get; set; }
public IndexModel(Database database, ILogger<IndexModel> logger)
{
this.database = database;
this.logger = logger;
}
public void OnGet() {}
public IActionResult OnPostValidate()
{
if (ModelState.IsValid)
{
// ...
}
return new BadRequestObjectResult(ModelState);
}
public async Task<IActionResult> OnPutConfirmAsync()
{
// ...
}
}
And the client side post:
const url = "?handler=validate";
const data = { MyRequest: this.fields };
await axios.post(url, data);
I have verified the data is being submitted correctly:
That X-XSRF-TOKEN header is being added by axios before the request is submitted. The fact that the server responds with a list of errors indicates that it's not the XSRF token causing the problem:
Note the MyRequest object does not contain the values from the request payload - it was not bound as expected (FirstName would not return a required error otherwise). How can I tell RazorPages to accept the JSON request and bind it to my property?
I was able to get the Binding works by adding FromBody similar to how it worked for ASP.NET Web API 2.
[BindProperty, FromBody]
public BroadcastMessageEditingViewModel BindingInfo { get; set; }
Use urlsearchparams with formdata.
In this post you can find more information How do I post form data with fetch api?
You would be better off posting your data to an API endpoint instead of a page controller. Create a class from ControllerBase and it will handle your JSON post correctly.

Get the route value from url in webapi attribute routing

I have a webAPI controller which is like
Public class TestController:APIController
{
[Route(“Api/Test/{testId}/SubTest”)]
Public void Post(int subTestid)
{
}
}
Our requirement is to get the value of testId from the url inside the post method.
Could anyone suggest the best way to achieve this.
Looking at this link: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
The string "customers/{customerId}/orders" is the URI template for the
route. Web API tries to match the request URI to the template. In this
example, "customers" and "orders" are literal segments, and
"{customerId}" is a variable parameter.
public class OrdersController : ApiController
{
[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }
}
It seems that you need to change subTestid to testId so it will be a match.