Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Api Post Call Example #5649


User avatar
0
muhittincelik created

Hi,

Can you show me an api post example for your ConsoleApiClient application.

For example : /api/services/app/User/CreateOrUpdateUser

Thanks


18 Answer(s)
  • User Avatar
    0
    alper created
    Support Team
  • User Avatar
    0
    muhittincelik created

    This usage is OK ?

    using (var client = new HttpClient())
            {
                CreateOrUpdateUserInput usercontent = new CreateOrUpdateUserInput();
                    usercontent.User.Name = "Dilek";
                    usercontent.User.Surname = "Çelik";
                    usercontent.User.UserName = "Dilek";
                    
              var usercontent2 = new StringContent(JsonConvert.SerializeObject(usercontent), Encoding.UTF8, "application/json");
                    
                    var response = await client.PostAsync($"{ServerUrlBase}api/services/app/User/CreateOrUpdateUser", usercontent2);
    
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Data posted");
                    }
                    else
                    {
                        Console.WriteLine($"Failed to poste data. Status code:{response.StatusCode}");
                    }
            }
    
  • User Avatar
    0
    alper created
    Support Team

    You need to add the bearer authorization header as well!

    You can see how AbpApiClient adds the authorization header to the request.

    To get bearer token you can make a post to api/TokenAuth/Authenticate See AccessTokenManager class. It gets the authentication token for Abp.

  • User Avatar
    0
    muhittincelik created

    I use the following input at Swagger and execute. But i got Bad Request Error ( I logged in web site for access token at another session)

    GetUserList running at Swagger.

    { "User": { "Id": null, "Name": "Dilek", "Surname": "Çelik", "UserName": "Dilek", "EmailAddress": "[email protected]", "PhoneNumber": null, "Password": null, "IsActive": false, "ShouldChangePasswordOnNextLogin": false, "IsTwoFactorEnabled": false, "IsLockoutEnabled": false }, "AssignedRoleNames": [ "Test" ], "SendActivationEmail": false, "SetRandomPassword": false, "OrganizationUnits": [] }

  • User Avatar
    0
    muhittincelik created

    I got Internal Server Error with the following code;

    using (var client = new HttpClient())
    {
    	client.SetBearerToken(accessToken);
    
    	CreateOrUpdateUserInput usercontent = new CreateOrUpdateUserInput();
    	usercontent.User = new UserEditDto();
    
    	usercontent.User.Name = "Dilek";
    	usercontent.User.Surname = "Çelik";
    	usercontent.User.UserName = "Dilek";
    	usercontent.User.EmailAddress = "[email protected]";
    	usercontent.AssignedRoleNames = new string[] { "Test" };
    	usercontent.OrganizationUnits = new System.Collections.Generic.List<long> { 0 };
    
    	string a = JsonConvert.SerializeObject(usercontent);
    
    	var usercontent2 = new StringContent(a, Encoding.UTF8, "application/json");
    	
    	var response = await client.PostAsync($"{ServerUrlBase}api/services/app/User/CreateOrUpdateUser", usercontent2);
    
    	if (response.IsSuccessStatusCode)
    	{
    		Console.WriteLine("Data posted");
    	}
    	else
    	{
    		Console.WriteLine($"Failed to poste data. Status code:{response.StatusCode}");
    	}
    }
    
  • User Avatar
    0
    alper created
    Support Team

    what is the value of accessToken? See the server logs to understand what's the exception.

  • User Avatar
    0
    muhittincelik created

    AccessToken is right. I am using ConsoleApi example. I can get UserList with same token.

  • User Avatar
    0
    alper created
    Support Team

    So you have a problem with your input data! Is Test a valid role name in the database? Are you sure you have no records with the username Dilek. You need to check the Logs.txt in your web site.

  • User Avatar
    0
    muhittincelik created

    I can not run any POST api from swagger.

    For example "/api/services/app/Account/IsTenantAvailable". It is so simple. It has 1 parameter and that is tenant name.

    But i got Bad Request error. All POST request got "400 BAD REQUEST" error.

  • User Avatar
    0
    alper created
    Support Team

    In Swagger there's Authorize button. Did you authorize before executing an action?

  • User Avatar
    0
    muhittincelik created

    There is no Authorize button.

    But i logged in Admin WebPage at another chrome session and swagger can use this authorize token.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @muhittincelik,

    There are two problems in your example code;

    1. you need to set usercontent.User.Password = "password"; which is required.
    2. You shouldn't send 0 in the OrganizationUnits list. You can leave it empty like below
    usercontent.OrganizationUnits = new System.Collections.Generic.List<long> { }; 
    
  • User Avatar
    0
    muhittincelik created

    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.<OnAuthorizationAsync>d__3.MoveNext() INFO 2018-09-26 16:18:02,009 [48 ] ore.Mvc.Internal.ControllerActionInvoker - Authorization failed for the request at filter 'Abp.AspNetCore.Mvc.Antiforgery.AbpAutoValidateAntiforgeryTokenAuthorizationFilter'. INFO 2018-09-26 16:18:02,009 [48 ] icrosoft.AspNetCore.Mvc.StatusCodeResult - Executing HttpStatusCodeResult, setting HTTP status code 400 INFO 2018-09-26 16:18:02,009 [48 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Smart.Authorization.Users.UserAppService.CreateOrUpdateUser (Smart.Application) in 1.6294ms INFO 2018-09-26 16:18:02,009 [48 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 6.4975ms 302 INFO 2018-09-26 16:18:02,009 [48 ] Microsoft.AspNetCore.Server.Kestrel - Connection id "0HLH3M77B9UAJ", Request id "0HLH3M77B9UAJ:00000003": the application completed without reading the entire request body. INFO 2018-09-26 16:18:02,066 [49 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 GET http://sdprdcm01/Error?statusCode=400
    INFO 2018-09-26 16:18:02,071 [49 ] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {action = "Index", controller = "Error", area = ""}. Executing action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) INFO 2018-09-26 16:18:02,072 [49 ] ore.Mvc.Internal.ControllerActionInvoker - Executing action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) with arguments (400) - Validation state: Valid INFO 2018-09-26 16:18:02,073 [49 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc), returned result Microsoft.AspNetCore.Mvc.ViewResult in 0.4623ms. INFO 2018-09-26 16:18:02,073 [49 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executing ViewResult, running view Error. INFO 2018-09-26 16:18:02,075 [49 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executed ViewResult - view Error executed in 1.865ms. INFO 2018-09-26 16:18:02,075 [49 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) in 3.4141ms INFO 2018-09-26 16:18:02,075 [49 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 9.1511ms 200 text/html; charset=utf-8 INFO 2018-09-26 16:18:03,547 [11 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 GET http://wpad.finansbank.com.tr/wpad.dat
    INFO 2018-09-26 16:18:03,548 [11 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 1.4348ms 302 INFO 2018-09-26 16:18:03,549 [42 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 GET http://wpad.finansbank.com.tr/Error?statusCode=404
    INFO 2018-09-26 16:18:03,552 [42 ] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {action = "Index", controller = "Error", area = ""}. Executing action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) INFO 2018-09-26 16:18:03,553 [42 ] ore.Mvc.Internal.ControllerActionInvoker - Executing action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) with arguments (404) - Validation state: Valid INFO 2018-09-26 16:18:03,553 [42 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc), returned result Microsoft.AspNetCore.Mvc.ViewResult in 0.0174ms. INFO 2018-09-26 16:18:03,553 [42 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executing ViewResult, running view Error404. INFO 2018-09-26 16:18:03,556 [42 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executed ViewResult - view Error404 executed in 2.239ms. INFO 2018-09-26 16:18:03,556 [42 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) in 3.111ms INFO 2018-09-26 16:18:03,556 [42 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 6.4078ms 200 text/html; charset=utf-8 INFO 2018-09-26 16:19:00,188 [38 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 POST http://sdprdcm01/api/services/app/User/CreateOrUpdateUser application/json 235 INFO 2018-09-26 16:19:00,193 [38 ] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {area = "app", action = "CreateOrUpdateUser", controller = "User"}. Executing action Smart.Authorization.Users.UserAppService.CreateOrUpdateUser (Smart.Application) INFO 2018-09-26 16:19:00,193 [38 ] idateAntiforgeryTokenAuthorizationFilter - Antiforgery token validation failed. The required antiforgery header value "X-XSRF-TOKEN" is not present. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery header value "X-XSRF-TOKEN" is not present. at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.<ValidateRequestAsync>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.<OnAuthorizationAsync>d__3.MoveNext() INFO 2018-09-26 16:19:00,193 [38 ] ore.Mvc.Internal.ControllerActionInvoker - Authorization failed for the request at filter 'Abp.AspNetCore.Mvc.Antiforgery.AbpAutoValidateAntiforgeryTokenAuthorizationFilter'. INFO 2018-09-26 16:19:00,193 [38 ] icrosoft.AspNetCore.Mvc.StatusCodeResult - Executing HttpStatusCodeResult, setting HTTP status code 400 INFO 2018-09-26 16:19:00,193 [38 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Smart.Authorization.Users.UserAppService.CreateOrUpdateUser (Smart.Application) in 0.6725ms INFO 2018-09-26 16:19:00,193 [38 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 5.7674ms 302 INFO 2018-09-26 16:19:00,193 [38 ] Microsoft.AspNetCore.Server.Kestrel - Connection id "0HLH3M77B9UAJ", Request id "0HLH3M77B9UAJ:00000005": the application completed without reading the entire request body. INFO 2018-09-26 16:19:00,247 [13 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 GET http://sdprdcm01/Error?statusCode=400
    INFO 2018-09-26 16:19:00,261 [13 ] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {action = "Index", controller = "Error", area = ""}. Executing action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) INFO 2018-09-26 16:19:00,263 [13 ] ore.Mvc.Internal.ControllerActionInvoker - Executing action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) with arguments (400) - Validation state: Valid INFO 2018-09-26 16:19:00,264 [13 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action method Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc), returned result Microsoft.AspNetCore.Mvc.ViewResult in 0.7943ms. INFO 2018-09-26 16:19:00,265 [13 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executing ViewResult, running view Error. INFO 2018-09-26 16:19:00,270 [13 ] Core.Mvc.ViewFeatures.ViewResultExecutor - Executed ViewResult - view Error executed in 5.6589ms. INFO 2018-09-26 16:19:00,270 [13 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Smart.Web.Controllers.ErrorController.Index (Smart.Web.Mvc) in 8.8637ms INFO 2018-09-26 16:19:00,271 [13 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 24.1286ms 200 text/html; charset=utf-8

  • User Avatar
    0
    ismcagdas created
    Support Team

    @muhittincelik are you getting the error in ConsoleApiClient console application or on the swagger UI ? If you are running the ConsoleApiClient, Antiforgery token validation shouldn't happen.

  • User Avatar
    0
    muhittincelik created

    From Swagger UI.

    I want to use a POST request from ConsoleApiClient but i can not do that.

    In our desktop application, we have a job which gets database server details and insert database. I want to insert this details to your framework and use web interface.

    So i need insert, delete via Web Api examples from ConsoleApiClient.

    Thanks

  • User Avatar
    0
    muhittincelik created

    Can you connect our environment via webex ?

  • User Avatar
    0
    muhittincelik created

    I commented the following line at Startup.cs

    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

    Now it is working from ConsoleApiClient and Swagger.

    PS. But Role names can not find with Display Name. It can found with name and name is meaningless word at database side.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @muhittincelik

    If you are making the request from swagger-ui, then Antiforgery Validation will happen.

    When you make the request from a non-browser client, Antiforgery Validation should not happen. Have you tried my suggestion https://support.aspnetzero.com/QA/Questions/5649#answer-cb875964-8762-06f2-173a-39e92881ec82 ? It should work on ConsoleApiClient.