locked
Convert "var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Url.Scheme);" to .net core 2 RRS feed

  • Question

  • User-1849651236 posted

    Hello,

    Is there a forum where I can ask for help to convert this from Asp.Net 4.5.2 to Asp.Net Core 2.0?

    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Url.Scheme);

    It gives the error "error CS1061: 'HttpRequest' does not contain a definition for 'Url' and no extension method 'Url' accepting a first argument of type 'HttpRequest' could be found".

    Any help would be gratefully appreciated.

    Thanks,
    Tony

    Wednesday, June 13, 2018 1:00 PM

All replies

  • User1120430333 posted

    Like ASP.NET CORE that is in ASP.NET forums? 

    Wednesday, June 13, 2018 2:06 PM
  • Wednesday, June 13, 2018 6:01 PM
  • User-1849651236 posted

    Hello,

    I tried this:

    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Scheme);

    and Request is null.

    Thanks,
    Tony

    Wednesday, June 13, 2018 9:31 PM
  • User475983607 posted

    and Request is null.

    That's a design problem because code is invoke via a request in web applications.  Why is the request null?

    Maybe redirectUrl is empty because there are no routes named "GetAccessToken"?

    Anyway, this works.

        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                var redirectUrl = Url.RouteUrl("default", null, Request.Scheme);
                return Content(redirectUrl);
                //return View();
            }

    Can you post more code or code that reproduces the issue.

    Wednesday, June 13, 2018 10:14 PM
  • User-1849651236 posted

    Thanks for your help with this.  Here is my whole controller:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using ChinavasionAPI.Data;
    using ChinavasionAPI.Models;
    using ChinavasionAPI.Models.CAPIViewModels;
    using ChinavasionAPI.Managers;
    using ChinavasionAPI.Parameters;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.Rendering;using Newtonsoft.Json;
    using Microsoft.AspNetCore.Http;
    
    namespace ChinavasionAPI.Controllers
    {
         public class APIController : Controller
         {
              private readonly ChinavasionAPIContext _context;
    
              public APIController(ChinavasionAPIContext context)
              {
                   _context = context;
              }
    
              public IActionResult Index()
              {
                   return View();
              }
    
              [HttpGet]
              public async Task<IActionResult> Process()
              {
                   var viewModel = new SetupIndexData();
                   viewModel.Setups = await _context.Setups.ToListAsync();
    
                   return View(viewModel);
              }
    
              [HttpPost]
              public async Task<IActionResult> Process(IFormCollection formCollection, string parameterName, string parameterValue)
              {
                   string serverUrl = formCollection["SetupText"].ToString();
                   string queryCall = formCollection["QueryCallText"].ToString();
                   int? setupID = Convert.ToInt16(formCollection["SetupID"]);
    
                   if (setupID == null)
                   {
                        return NotFound();
                   }
    
                   var setup = await _context.Setups
                       .SingleOrDefaultAsync(m => m.ID == setupID);
                   if (setup == null)
                   {
                        return NotFound();
                   }
    
                   string serverKey = setup.Key;
    
                   var model = new AccessModel();
                   model.UserAccessModel = _context.UserAccessModels.Single(a => a.ID == 1);
                   ViewBag.SyncOrAsync = "Asynchronous";
                   var productsService = new Service.ProductService();
                   List<Product> products = (await productsService.ProcessAPIAsync(serverUrl, serverKey, queryCall, parameterName, parameterValue));
    
                   if (ModelState.IsValid)
                   {
                        try
                        {
                             var nopAuthorizationManager = new AuthorizationManager(model.UserAccessModel.ClientId, model.UserAccessModel.ClientSecret, model.UserAccessModel.ServerUrl);
    
                             var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Scheme);
    
                             if (redirectUrl != model.UserAccessModel.RedirectUrl)
                             {
                                  return BadRequest();
                             }
    
                             // This should not be saved anywhere.
                             var state = Guid.NewGuid();
                             //Session["state"] = state;
    
                             string authUrl = nopAuthorizationManager.BuildAuthUrl(redirectUrl, new string[] { }, state.ToString());
    
                             return Redirect(authUrl);
                        }
                        catch (Exception ex)
                        {
                             return BadRequest(ex.Message);
                        }
                   }
    
                   return BadRequest();
    
                   //return View("~/Views/Home/Products.cshtml", submitMethod.Submit(model.UserAccessModel));
              }
    
              [HttpGet]
              [AllowAnonymous]
              public ActionResult GetAccessToken(string code, string state)
              {
                   if (ModelState.IsValid && !string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
                   {
                        var model = new AccessModel();
                        model.UserAccessModel = _context.UserAccessModels.Single(a => a.ID == 1);
    
                        try
                        {
                             string clientId = model.UserAccessModel.ClientId;
                             string clientSecret = model.UserAccessModel.ClientSecret;
                             string serverUrl = model.UserAccessModel.ServerUrl;
                             string redirectUrl = model.UserAccessModel.RedirectUrl;
    
                             var authParameters = new AuthParameters()
                             {
                                  ClientId = clientId,
                                  ClientSecret = clientSecret,
                                  ServerUrl = serverUrl,
                                  RedirectUrl = redirectUrl,
                                  GrantType = "authorization_code",
                                  Code = code
                             };
    
                             var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId, authParameters.ClientSecret, authParameters.ServerUrl);
    
                             string responseJson = nopAuthorizationManager.GetAuthorizationData(authParameters);
    
                             AuthorizationModel authorizationModel = JsonConvert.DeserializeObject<AuthorizationModel>(responseJson);
    
                             model.AuthorizationModel = authorizationModel;
                             model.UserAccessModel = new UserAccessModel()
                             {
                                  ClientId = clientId,
                                  ClientSecret = clientSecret,
                                  ServerUrl = serverUrl,
                                  RedirectUrl = redirectUrl
                             };
    
                             // TODO: Here you can save your access and refresh tokens in the database. For illustration purposes we will save them in the Session and show them in the view.
                             //Session["accessToken"] = authorizationModel.AccessToken;
                             model.UserAccessModel.AccessToken = authorizationModel.AccessToken;
                        }
                        catch (Exception ex)
                        {
                             return BadRequest(ex.Message);
                        }
    
                        return View("~/Views/API/AccessToken.cshtml", model);
                   }
    
                   return BadRequest();
              }
    
              [HttpGet]
              [AllowAnonymous]
              public JsonResult RefreshAccessToken(string refreshToken, string clientId, string clientSecret, string serverUrl)
              {
                   string json = string.Empty;
    
                   if (ModelState.IsValid &&
                       !string.IsNullOrEmpty(refreshToken) &&
                       !string.IsNullOrEmpty(clientId) &&
                        !string.IsNullOrEmpty(clientSecret) &&
                       !string.IsNullOrEmpty(serverUrl))
                   {
                        var model = new AccessModel();
    
                        try
                        {
                             var authParameters = new AuthParameters()
                             {
                                  ClientId = clientId,
                                  ClientSecret = clientSecret,
                                  ServerUrl = serverUrl,
                                  RefreshToken = refreshToken,
                                  GrantType = "refresh_token"
                             };
    
                             var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId,
                                 authParameters.ClientSecret, authParameters.ServerUrl);
    
                             string responseJson = nopAuthorizationManager.RefreshAuthorizationData(authParameters);
    
                             AuthorizationModel authorizationModel =
                                 JsonConvert.DeserializeObject<AuthorizationModel>(responseJson);
    
                             model.AuthorizationModel = authorizationModel;
                             model.UserAccessModel = new UserAccessModel()
                             {
                                  ClientId = clientId,
                                  ServerUrl = serverUrl
                             };
    
                             // Here we use the temp data because this method is called via ajax and here we can't hold a session.
                             // This is needed for the GetCustomers method in the CustomersController.
                             TempData["accessToken"] = authorizationModel.AccessToken;
                             TempData["serverUrl"] = serverUrl;
                        }
                        catch (Exception ex)
                        {
                             json = string.Format("error: '{0}'", ex.Message);
    
                             //return Json(json, JsonRequestBehavior.AllowGet);
                             return Json(json);
    
                        }
    
                        json = JsonConvert.SerializeObject(model.AuthorizationModel);
                   }
                   else
                   {
                        json = "error: 'something went wrong'";
                   }
    
                   return Json(json);
    
              }
    
              private ActionResult BadRequest(string message = "Bad Request")
              {
                   //return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
                   return new StatusCodeResult(404);
              }
         }
    }

    Thanks,
    Tony

    Thursday, June 14, 2018 2:06 PM
  • User475983607 posted

    I don't anything in the code that would cause a null request.  You must have a design bug or there is something else going on that you're not telling us.

    Run the code through the Visual Studio debugger.  

    Thursday, June 14, 2018 7:23 PM
  • User-1849651236 posted

    Yes, I am using the Visual Studio debugger.   That's how I know it is returning null.

    On this statement:

    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Scheme);

    The Request.Scheme shows 'http' as expected.

    If I put a watch on Url.RouteUrl, it shows "error CS0428: Cannot convert method group 'RouteUrl' to non-delegate type 'object'. Did you intend to invoke the method?"

    Thanks,
    Tony

    Thursday, June 14, 2018 8:14 PM
  • User475983607 posted

    TGirgenti

    Yes, I am using the Visual Studio debugger.   That's how I know it is returning null.

    On this statement:

    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Scheme);

    The Request.Scheme shows 'http' as expected.

    Ok, my first response fixed your syntax error.

    TGirgenti

    If I put a watch on Url.RouteUrl, it shows "error CS0428: Cannot convert method group 'RouteUrl' to non-delegate type 'object'. Did you intend to invoke the method?"

    I did not try it but I assume the error is the expected behavior when watching a method without the parameters.  As a matter of fact if you read the CS0428 error it states...

    This error occurs when converting a method group to a non-delegate type, or attempting to invoke a method without using parentheses.

    Do you have an actual issue?  Is redirectUrl empty?  If so, do you have a route named GetAccessToken?

    Thursday, June 14, 2018 9:05 PM
  • User-1849651236 posted

    Yes, the issue is redirectUrl is null.

    I do not have a route named GetAccessToken.  Where would I put that.

    Thanks,
    Tony

    Thursday, June 14, 2018 9:28 PM
  • User475983607 posted

    TGirgenti

    Yes, the issue is redirectUrl is null.

    That's a new issue!  

    Routes are defined in the Configure method in Startup.cs and look similar to the following.

            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //Omitted for brevity
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    ASP Core also uses attribute routing.  You might have a Web API route like this for example.

        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET: api/Values
            [HttpGet(Name = "GetAccessToken")]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }

    Reading the documentation helps alot with questions like this.

    Attribute routing in ASP Core

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1

    TGirgenti

    I do not have a route named GetAccessToken.  Where would I put that.

    Tony, I have no idea how your application works.  Maybe you can get a team member and hash out the details?

    Thursday, June 14, 2018 10:08 PM
  • User-1849651236 posted


    That's a new issue!

    Should I start a different post?

    My Startup.cs only had one default route, so I added this route:

                     routes.MapRoute(
                        name: "GetAccessToken",
                        template: "{controller=API}/{action=GetAccessToken}");
    

    It gave me a value in redirectUrl, but it is not what I was expecting.


    Tony, I have no idea how your application works. Maybe you can get a team member and hash out the details?

    By "team member" do you mean someone here where I am working?

    Thanks for your help.

    Tony

    Friday, June 15, 2018 10:38 AM
  • User475983607 posted

    It gave me a value in redirectUrl, but it is not what I was expecting.

    We cannot read your mind Tony.  What are you expecting?

    By "team member" do you mean someone here where I am working?

    Yes, ask your team for help if you do not understand what you're upgrading or how the application works.  You're asking the wrong audience as we, on the forum, cannot see the code base.

    Saturday, June 16, 2018 12:32 PM