question

fahimeabouhamze-7844 avatar image
0 Votes"
fahimeabouhamze-7844 asked cooldadtx answered

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

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.

dotnet-csharpdotnet-aspnet-general
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This error pops up when the controller contains a constructor with parameters and no parameter less constructor. Simply add a parameter less constructor to the controller.

1 Vote 1 ·

1 Answer

cooldadtx avatar image
0 Votes"
cooldadtx answered

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 )
{
}
}
```

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.