Call a rest web api in asp.net in order to get token but recive error

fahime abouhamze 126 Reputation points
2021-09-24T13:25:27.68+00:00

Hi I want to call a rest Web Api and I use asp.net MVC+Web Api I write a get Token Method like bellow :

  public TokenViewModel GetToken()
{
    //string Result = string.Empty;
    TokenViewModel token = null;
    string baseAddress = "http://$$$$$$$$$$/api/security/login";
    using (HttpClient client = new HttpClient())
    {
        try
        {
            var url = new Uri(baseAddress);
            MultipartFormDataContent form = new MultipartFormDataContent();
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("UserName", "###");
            parameters.Add("Password", "$$$");
            HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
            form.Add(DictionaryItems, "model");


            var response = client.PostAsync(url.ToString(), form,            System.Threading.CancellationToken.None);

            if (response.Result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //Get body
                var bodyRes = response.Result.Content.ReadAsStringAsync().Result;
                token = JsonConvert.DeserializeObject<TokenViewModel>(bodyRes);
                //Get Header
                //   var headers = response.Result.Headers.GetValues("appToken");
            }
            else
            {
                var a = response.Result.Content.ReadAsStringAsync().Result;
            }
        }
        catch (Exception ex)
        {

        }
        return token;

    }

}

and also webController :

[HttpPost]
[Route("api/Token")]
public IHttpActionResult Token()
{
stcAPIMessage message = new stcAPIMessage();
GetToken_BLL tokenbll = new GetToken_BLL();
var result = tokenbll.GetToken();

    if (result == null)
    {
        message.Message = "Error in receiving Token!! ";
        message.StatusCode = HttpStatusCode.BadRequest;
        return Content(message.StatusCode, message.Message);
    }
    else if (string.IsNullOrEmpty(result.Token))
    {
        message.Message = "Error";
        message.StatusCode = HttpStatusCode.BadRequest;
        return Content(message.StatusCode, message.Message);
    }
    return Ok(result);
}

when I run the program it throw out error: /* An error occurred when trying to create a controller of type 'Web ApiController'. Make sure that the controller has a parameter less public constructor. System. Invalid Operation Exception Type 'WebAPI.Controllers. Web ApiController' does not have a default constructor System.

Developer technologies ASP.NET Other
Developer technologies C#
{count} vote

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2021-09-24T14:22:52.983+00:00

    Out of the box ASP.NET MVC does not support dependency injection like the newer ASP.NET Core runtime does. Therefore your controllers cannot require any parameters. That also means your controllers are responsible for creating any "services" that they need. This is a maintenance nightmare and not recommended.

    It is generally recommended that you set up DI for your project so that your controllers can accept parameters. DI frameworks hook into the creation of controllers and are able to create controllers with parameters. You configure your dependencies at app startup and the DI container handles everything from there. All DI libraries support ASP.NET MVC so you just need to pick one, download the NuGet package for it and follow the steps it gives to hook things up. As an example Autofac is one that I've traditionally used for an MVC app.

    //App startup
    var builder = new ContainerBuilder();
    
    //Register Autofac to handle MVC and API Controller creation
    builder.RegisterControllers(Assembly.GetExecutingAssembly());
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
    //Register any types you want to be able to pass to controllers (or dependencies of controllers)
    builder.RegisterType<MyService>().AsSelf();
    
    //After you have registered everything you have to hook it up to the MVC & API infrastructure
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container); //config is the HttpConfiguration
    

    Now you can use parameterized controllers (and actually any types), just make sure each type that is used is registered in the container

    public class MyController : Controller
    {
        public MyController ( MyService service )
        {
        }
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.